Leetcode 453 Minimum Moves to Equal Array Elements

Source: Internet
Author: User

Problem:

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements E Qual, where a move is incrementing n -1 elements by 1.

Example:

Input:[1,2,3]output:3explanation:only three moves is needed (remember each move increments both elements): [+]  =& gt;  [2,3,3]  =  [3,4,3]  =  [4,4,4]

Summary:

For an array of integers of length n, each step adds 1 to the n-1 element, which requires a minimum number of steps to make the numbers in the array all the same.

Analysis:

Shut up array to meet the requirements of the problem as soon as possible, you need to remove the maximum value of the remaining number plus 1, but this method is too inefficient, you can change a way of thinking. Each time the n-1 number in the array is added 1, it is equivalent to minus 1 of the remaining number. So just find the minimum m in the array and calculate the accumulation of the difference between M and the other numbers in the array.

1 classSolution {2  Public:3     intMinmoves (vector<int>&nums) {4 sort (Nums.begin (), Nums.end ());5         intLen = Nums.size (), res =0;6         7          for(inti =1; i < Len; i++) {8Res + = Nums[i]-nums[0];9         }Ten          One         returnRes; A     } -};

Leetcode 453 Minimum Moves to Equal Array Elements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.