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

 Live Demo

#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

Updated on: 02-Sep-2020

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements