Java O(n) Accepted Solution With Explanation

  • 3

    The effect of increasing n-1 elements by one is equal to decrease the left element by one. The goal is to decrease every element larger than the minimum element to the minimum element. So, the number of operation needed is sum-min*(nums.length).

        public int minMoves(int[] nums) {
            if (nums.length <= 1) return 0;
            int min = Integer.MAX_VALUE;
            int sum = 0;
            for (int i = 0; i < nums.length; i++) {
                sum += nums[i];
                min = Math.min(min, nums[i]);
            return sum-nums.length*min;

  • 1

    simple and awesome idea!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.