Decrease Elements To Make Array Zigzag - Problem
Transform an array into a zigzag pattern using the minimum number of moves! ๐ฏ
Given an array nums of integers, you can perform moves where each move consists of decreasing any element by 1. Your goal is to create a zigzag array with the fewest possible moves.
A zigzag array follows one of these patterns:
- Pattern 1: Even indices are peaks โ
A[0] > A[1] < A[2] > A[3] < A[4] > ... - Pattern 2: Odd indices are peaks โ
A[0] < A[1] > A[2] < A[3] > A[4] < ...
Example: [1,17,5,10,13,15,10,5,16,8] can become zigzag by making strategic decreases!
Return the minimum number of moves needed to transform the array into either zigzag pattern.
Input & Output
example_1.py โ Basic Zigzag
$
Input:
[1,17,5,10,13,15,10,5,16,8]
โบ
Output:
4
๐ก Note:
We can make this zigzag by adjusting valley positions. For even-indexed valleys: decrease index 2 (5โ4), index 4 (13โ9), index 6 (10โ5), index 8 (16โ5). Total moves: 1+4+5+11 = 21. For odd-indexed valleys: decrease index 1 (17โ0), index 3 (10โ4), index 5 (15โ9), etc. We choose the minimum between both patterns.
example_2.py โ Small Array
$
Input:
[2,7,10,9,8,9]
โบ
Output:
4
๐ก Note:
Pattern 1 (even valleys): [1,7,1,9,1,9] needs 1+9+7=17 moves. Pattern 2 (odd valleys): [2,6,10,8,8,9] needs 1+0+1+0=2 moves. But after checking constraints: [2,1,10,1,8,9] needs 6+8=14 moves for pattern 2. The minimum is 4 moves.
example_3.py โ Already Zigzag
$
Input:
[9,6,1,6,2]
โบ
Output:
0
๐ก Note:
This array is already in zigzag pattern (9>6<1>6>2), following the odd-peaks pattern. No moves needed.
Constraints
- 1 โค nums.length โค 1000
- 1 โค nums[i] โค 1000
- Only decreasing moves allowed - you cannot increase any element
- Two valid zigzag patterns exist - choose the one requiring fewer moves
Visualization
Tap to expand
Understanding the Visualization
1
Identify Patterns
Two possible zigzag patterns: even-peaks or odd-peaks
2
Calculate Pattern 1
Make even indices valleys, count required moves
3
Calculate Pattern 2
Make odd indices valleys, count required moves
4
Choose Optimal
Select the pattern requiring minimum earth removal
Key Takeaway
๐ฏ Key Insight: Only valley positions need adjustment! Peaks can remain unchanged, making this a simple O(n) greedy solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code