Skip to content

1144. Decrease Elements To Make Array Zigzag

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int movesToMakeZigzag(vector<int>& nums) {
    vector<int> decreasing(2);

    for (int i = 0; i < nums.size(); ++i) {
      int l = i > 0 ? nums[i - 1] : 1001;
      int r = i + 1 < nums.size() ? nums[i + 1] : 1001;
      decreasing[i % 2] += max(0, nums[i] - min(l, r) + 1);
    }

    return min(decreasing[0], decreasing[1]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int movesToMakeZigzag(int[] nums) {
    int[] decreasing = new int[2];

    for (int i = 0; i < nums.length; ++i) {
      int l = i > 0 ? nums[i - 1] : 1001;
      int r = i + 1 < nums.length ? nums[i + 1] : 1001;
      decreasing[i % 2] += Math.max(0, nums[i] - Math.min(l, r) + 1);
    }

    return Math.min(decreasing[0], decreasing[1]);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def movesToMakeZigzag(self, nums: List[int]) -> int:
    decreasing = [0] * 2

    for i, num in enumerate(nums):
      l = nums[i - 1] if i > 0 else 1001
      r = nums[i + 1] if i + 1 < len(nums) else 1001
      decreasing[i % 2] += max(0, num - min(l, r) + 1)

    return min(decreasing[0], decreasing[1])