Decrease Elements To Make Array Zigzag

For this task, I did not complete it during the contest. This is taged by easy!

class Solution {
    public int movesToMakeZigzag(int[] nums) {
        int[] res = new int[2];
        int len = nums.length, left, right;
        for (int i = 0; i < len; i++) {
            left = i > 0 ? nums[i - 1] : 1001;
            right = i < len - 1 ? nums[i + 1] : 1001;
            res[ i % 2] += Math.max(0, nums[i] - Math.min(left, right) + 1);
        }
        return Math.min(res[0], res[1]);
    }
}

Answer is referenced by this [discussion] (https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/350576/JavaC%2B%2BPython-Easy-and-concise)

...When the index is 0, left is out of boundary, so give this value a mock 1001, which is greater max in this nums

...When the index is length - 1, right is out of boundary, so give this value a mock 1001, which is greater max in this nums

猜你喜欢

转载自www.cnblogs.com/setnull/p/11318727.html