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 elements 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]
Subject to the effect :
Given non-empty array, each element of the n-1 value by 1, until all elements of equal value, the minimum required number of moves.
Understanding:
See for Solving others, reverse thinking, the remaining elements added to the n-1 1, corresponding to the selected request element minus 1, i.e., find all the elements of the minimum difference value and a minimum number of mobile elements.
Code C ++:
class Solution { public: int minMoves(vector<int>& nums) { long sum = nums[0],min=nums[0]; for(int i=1;i<nums.size();++i){ sum += nums[i]; if(nums[i]<min) min = nums[i]; } return sum-min*nums.size(); } };
operation result:
When execution: 56 ms, beat the 80.44% of all users to submit in C ++
Memory consumption: 10.8 MB, defeated 85.59% of all users to submit in C ++