Program to count number of operations required to convert all values into same in Python?

PythonServer Side ProgrammingProgramming

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

 Live Demo

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
raja
Published on 10-Nov-2020 09:18:22
Advertisements