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
๐Ÿ”๏ธ Zigzag Mountain DesignerOriginal Mountain RangePattern 1: Even ValleysCost: X movesPattern 2: Odd ValleysCost: Y moves๐ŸŽฏ Choose Patternwith MIN(X, Y) moves
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.
Asked in
Facebook 15 Amazon 8 Google 5 Microsoft 3
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen