To make the array zigzag, we can either make even indices valleys (smaller than neighbors) or odd indices valleys. For each pattern, we count the moves needed to decrease elements so that every valley is strictly less than its neighbors. The answer is the minimum of the two patterns.
classSolution {
public:int movesToMakeZigzag(vector<int>& nums) {
int n = nums.size();
int ans[2] = {0, 0};
for (int parity =0; parity <2; ++parity) {
for (int i = parity; i < n; i +=2) {
int l = (i >0) ? nums[i-1] : INT_MAX;
int r = (i+1< n) ? nums[i+1] : INT_MAX;
int mn = min(l, r);
if (nums[i] >= mn) ans[parity] += nums[i] - mn +1;
}
}
returnmin(ans[0], ans[1]);
}
};
classSolution {
publicintmovesToMakeZigzag(int[] nums) {
int n = nums.length;
int[] ans =newint[2];
for (int parity = 0; parity < 2; parity++) {
for (int i = parity; i < n; i += 2) {
int l = i > 0 ? nums[i-1] : Integer.MAX_VALUE;
int r = i+1 < n ? nums[i+1] : Integer.MAX_VALUE;
int mn = Math.min(l, r);
if (nums[i]>= mn) ans[parity]+= nums[i]- mn + 1;
}
}
return Math.min(ans[0], ans[1]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funmovesToMakeZigzag(nums: IntArray): Int {
val n = nums.size
val ans = IntArray(2)
for (parity in0..1) {
for (i in parity until n step 2) {
val l = if (i > 0) nums[i-1] elseInt.MAX_VALUE
val r = if (i+1 < n) nums[i+1] elseInt.MAX_VALUE
val mn = minOf(l, r)
if (nums[i] >= mn) ans[parity] += nums[i] - mn + 1 }
}
return minOf(ans[0], ans[1])
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defmovesToMakeZigzag(self, nums: list[int]) -> int:
n: int = len(nums)
ans: list[int] = [0, 0]
for parity in (0, 1):
for i in range(parity, n, 2):
l = nums[i-1] if i >0else float('inf')
r = nums[i+1] if i+1< n else float('inf')
mn = min(l, r)
if nums[i] >= mn:
ans[parity] += nums[i] - mn +1return min(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmoves_to_make_zigzag(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans = [0, 0];
for parity in0..2 {
for i in (parity..n).step_by(2) {
let l =if i >0 { nums[i-1] } else { i32::MAX };
let r =if i+1< n { nums[i+1] } else { i32::MAX };
let mn = l.min(r);
if nums[i] >= mn {
ans[parity] += nums[i] - mn +1;
}
}
}
ans[0].min(ans[1])
}
}