Leetcode 453. Minimum Moves to Equal Array Elements C #

Source: Internet
Author: User

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]

Solution:

Incrementing n-1 elements by one, means every time need to increment 1 to every number except the maximum. But it's hard to implement.

Increment to every nums except Max, are as same as decrement 1 on one number until every number equals min number.

1  Public classSolution {2      Public intMinmoves (int[] nums) { 3         if(Nums. length==0)4         {5             return 0;6         }7         intn =Nums. Length;8         //Find min value in Nums;9         intMin =nums[0];Ten         foreach(intNuminchnums) One         { AMin =math.min (Min, num); -         } -          the         //Calculate the difference of every num from nums and min; ths sum should being the min Moves -         //Add 1 to n-1 are same as minus 1 from the max each time. -         intMoves =0; -         foreach(intNuminchnums) +         { -Moves + = (num-min); +         } A         returnmoves; at     } -}

Leetcode 453. Minimum Moves to Equal Array Elements C #

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.