
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Python - Total equal pairs in List
- How to save list where each element contains equal number of values to a text file in R?
- Group array by equal values JavaScript
- What is stainless steel? List the processes involved in making stainless steel.
- Check if two List objects are equal in C#
- Total possible ways of making sum of odd even indices elements equal in array in \nJavaScript
- MySQL Select where values IN List string?
- Python – Inverse Dictionary Values List
- Get unique values from a list in Python
- Sort list of dictionaries by values in C#
- Combining values from dictionary of list in Python
- Sort Dictionary key and values List in Python
- Python | Sort the values of first list using second list
- MySQL Query a List of Values?
- How can I sort one list by values from another list in Python?

Advertisements