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:
0
💡 Note:
Array [1,17,5] already follows zigzag pattern with odd indices as peaks: 1 < 17 > 5. No moves needed.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code