
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Operations to Convert All Values to Same in Python
Given a list of integers nums, you can perform the following operation: pick the largest number in nums and turn it into the second largest number. Return the minimum number of operations required to make all integers the same in the list.
So, if the input is like nums = [5, 9, 2], then the output will be 3, as pick 9 first, then make it 5, so array is [5, 5, 2], then pick 5 and make 2, [5, 2, 2], again pick 5 and convert into 2, [2, 2, 2].
To solve this, we will follow these steps
vals := sort the list of unique characters in nums
vtoi := a map for all values v in vals as key and their index i as value
return sum of vtoi[v] for all v in nums
Let us see the following implementation to get better understanding
Example
class Solution: def solve(self, nums): vals = sorted(set(nums)) vtoi = {v: i for i, v in enumerate(vals)} return sum(vtoi[v] for v in nums) ob = Solution() nums = [5, 9, 2] print(ob.solve(nums))
Input
[5, 9, 2]
Output
3
Advertisements