Leetcode-453 Minimum Moves to Equal Array Elements
#453. Minimum Moves to Equal Array Elements
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]
题解:每次加一的元素肯定是数组中最小的n-1和元素;
把最小的n-1个元素都加1,相当于所有元素都加1,最大的元素减一,因为题目要求最后的元素值相同即可,所以所有元素加一操作完全可以去掉,
即每一次的“移动”操作等价于把最大元素减一。最终状态为每个元素都等于初始数组的最小值,sum(nums)-min(nums)*len(nums)。
class Solution { public: int minMoves(vector<int>& nums) { sort(nums.begin(),nums.end()); int sum=0; for(int i=0;i<nums.size();i++) { sum+=nums[i]; } return sum-nums[0]*nums.size(); } };