(Java) Leetcode 453. Minimum Moves to Equal array elements--the minimum number of moves to make the elements equal

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]

Think and "algorithm" knowledge unrelated to the simple problem is a bit difficult ah ... First fixed every time to make n-1 element +1, then this n-1 must be the smallest n-1, otherwise it will become more and more. Always find the smallest n-1 to add, until all the numbers are equal. To change the angle, it is equal to find the maximum number each time to make it-1, until the maximum and minimum number are equal. Eventually, all the numbers that are larger than the smallest are going to be the smallest numbers. So, the result is to ask for all the numbers and the minimum number of deviations. That is, the sum of all numbers and the difference between the minimum and the length of the array. The subject is a logical and mathematical simplification. The feeling algorithm sometimes is the mathematics competition ah ...

Java

class Solution {    publicint minmoves (int[] nums) {        int min = Nums[0], sum = 0;          for (int  num:nums) {            if (num < min)                = num;             + = num        ;        } return sum-nums.length * min;    }}

(Java) Leetcode 453. Minimum Moves to Equal array elements--the minimum number of moves makes the elements equal to the

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.