Decrease Elements To Make Array Zigzag - Problem
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, i.e.
A[0] > A[1] < A[2] > A[3] < A[4] > ... - OR, every odd-indexed element is greater than adjacent elements, i.e.
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,17,5]
›
Output:
2
💡 Note:
We can choose pattern where odd indices are peaks: decrease 17→17 (no change), decrease 5→4 (1 move), decrease 1→0 (1 move). Result: [0,17,4] with 2 total moves.
Example 2 — All Equal
$
Input:
nums = [2,2,2]
›
Output:
1
💡 Note:
Make middle element peak: keep [2,2,2] but need one valley. Best is [1,2,1] requiring 2 moves, or [2,2,1] requiring 1 move for pattern with even peaks.
Example 3 — Already Zigzag
$
Input:
nums = [1,3,2,4,1]
›
Output:
0
💡 Note:
Array already follows zigzag pattern with odd indices as peaks: 1 < 3 > 2 < 4 > 1. No moves needed.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original array [1,17,5]
2
Process
Try both zigzag patterns and compare moves
3
Output
Return minimum moves needed: 2
Key Takeaway
🎯 Key Insight: Only two zigzag patterns exist - test both and choose the one requiring fewer moves
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code