Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 element by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Approach:
C++
#include <bits/stdc++.h>using namespace std;long long int minMoves(vector<int> &nums){long long int n = nums.size();long long int sum = 0;int min1 = INT_MAX;for (long long int i = 0; i < n; i++){sum += nums[i];min1 = min(nums[i], min1);}return sum - n * min1;}int main(){vector<int> nums = {1, 2, 3};cout << minMoves(nums);return 0;}
No comments:
Post a Comment