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
Decrease Elements To Make Array Zigzag INPUT nums = [1, 17, 5] 1 idx 0 17 idx 1 5 idx 2 Two Zigzag Patterns: Pattern A (even peaks): A[0] > A[1] < A[2] > ... Pattern B (odd peaks): A[0] < A[1] > A[2] < ... Pattern A Pattern B ALGORITHM STEPS 1 Try Pattern A Make evens greater idx1: need 17 < min(1,5) = 1 Cost: 17 - 0 = 17 moves 2 Try Pattern B Make odds greater idx0: need 1 < 17 OK (0 moves) idx2: need 5 < 17 OK (0 moves) Cost: 0 moves 3 Wait - Check Again! Pattern A: decrease odds idx1: 17 --> 0 (17 moves) But min needed: 17-->0 = 17 4 Compare Costs min(Pattern A, B) = min(17,2) Answer = 2 FINAL RESULT Optimal: Pattern B (odd peaks) Before: 1 17 5 After (2 moves): 1 17 3 1 < 17 5-->3 17 > 3 Output: 2 OK - Minimum moves found! Key Insight: Greedy approach: Try both zigzag patterns independently. For each pattern, only decrease the elements at valleys (not peaks). Each valley element must be strictly less than both neighbors. Return minimum of both patterns. Time: O(n), Space: O(1). TutorialsPoint - Decrease Elements To Make Array Zigzag | Greedy - Two Pattern Approach
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