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
Zigzag Array Transformation: Find Minimum Moves1175Input: [1, 17, 5]Two possible zigzag patterns:105Even peaks: 17 moves0174Odd peaks: 2 movesOutput: 2 (minimum moves)Choose the pattern requiring fewer decreasing moves
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
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
485 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