

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Making List Values Equal in C++
Suppose we have a list of integers called nums. Now suppose an operation where we select some subset of integers in the list and increment all of them by one. We have to find the minimum number of required operations to make all values in the list equal to each other.
So, if the input is like [1,3,5], then the output will be 4.
To solve this, we will follow these steps −
if size of nums is same as 1, then −
return 0
ret := 0
maxVal := -inf
minVal := inf
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
maxVal := maximum of maxVal and nums[i]
minVal := minimum of minVal and nums[i]
return maxVal - minVal
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int solve(vector<int> &nums) { if (nums.size() == 1) return 0; int ret = 0; int maxVal = INT_MIN; int minVal = INT_MAX; for (int i = 0; i < nums.size(); i++) { maxVal = max(maxVal, nums[i]); minVal = min(minVal, nums[i]); } return maxVal - minVal; } }; main() { Solution ob; vector<int> v = {1,3,5}; cout << (ob.solve(v)); }
Input
{1,3,5}
Output
4
- Related Questions & Answers
- Python - Total equal pairs in List
- Group array by equal values JavaScript
- Total possible ways of making sum of odd even indices elements equal in array in JavaScript
- Decision Making in C#
- Decision Making in Java
- Decision Making in C++
- Check if two List objects are equal in C#
- Making http request in React.js
- Making array unique in JavaScript
- How to save list where each element contains equal number of values to a text file in R?
- Making your first map in javascript
- Making A Large Island in C++
- Making two sequences increasing in JavaScript
- Java program without making class
- MySQL Select where values IN List string?
Advertisements