[LeetCode] Decrease Elements To Make Array Zigzag

1144. Decrease Elements To Make Array Zigzag

Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.

An array A is a zigzag array if either:

  • Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > …
  • OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < …

Return the minimum number of moves to transform the given array nums into a zigzag array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
int helper(vector<int>& A, int st) {
int res = 0, n = A.size();
for(int i = st; i < n; i += 2) {
int mi = INT_MAX;
if(i - 1 >= 0) mi = min(mi, A[i-1]);
if(i + 1 < n) mi = min(mi, A[i+1]);
if(mi <= A[i]) res += A[i] - mi + 1;
}
return res;
}
public:
int movesToMakeZigzag(vector<int>& A) {
return min(helper(A,0), helper(A,1));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/14/PS/LeetCode/decrease-elements-to-make-array-zigzag/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.