- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to count number of operations required to convert all values into 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
- Related Articles
- Program to count number of operations required to all cells into same color in Python
- Program to count minimum number of operations required to make numbers non coprime in Python?
- Program to count number of swaps required to group all 1s together in Python
- C++ Program to count operations to make all gifts counts same
- Number of operations required to make all array elements Equal in Python
- Program to count number of flipping required to make all x before y in Python
- Program to find number of operations needed to convert list into non-increasing list in Python
- Program to find number of given operations required to reach Target in Python
- Program to count number of operations needed to make string as concatenation of same string twice in Python
- Program to find minimum number of operations required to make one number to another in Python
- Count the number of operations required to reduce the given number in C++
- Program to count number of operations to convert binary matrix to zero matrix in C++
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Count the number of carry operations required to add two numbers in C++
- C++ program to count expected number of operations needed for all node removal

Advertisements