zoukankan      html  css  js  c++  java
  • 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]

    Approach #1: Math. [Java]

    class Solution {
        public int minMoves(int[] nums) {
            int len = nums.length;
            int sum = 0, minNum = Integer.MAX_VALUE;
            for (int n : nums) {
                sum += n;
                minNum = Math.min(minNum, n);
            }
            return sum - minNum * len;
        }
    }
    

      

    Analysis:

    Let's define sum as the sum of all the numbers, before any moves; minNum as the min number int the list; n is the length of the list;

    After, say m moves, we get all the numbers as x, and we will get the following equation:

    sum + m * (n - 1) = x * n;

    and actually:

    x = minNum + m;

    It comes from two observations:

    The minum number will always be minum unitl it reachs the final number, because every move, other numbers (besides the max) will be increamented too;

    From above, we can get, the minum number will be incremented in every move. So if the final number is x, it would be minNum + moves;

    and finally, we will get:

    sum - minNum * n = m;

    This is just a math calculation.

    Reference:

    https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93817/It-is-a-math-question

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    转移阵地啦
    春之感--3月10日
    小鱼儿
    关于时间方法(date和simpledateformat)的实验
    hadoop练习处理地震数据
    出现log4j.properties问题
    远程hadoop集群方法
    小W学物理
    灵知的太阳信仰
    Blue
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10853963.html
Copyright © 2011-2022 走看看