Decrease Elements To Make Array Zigzag Problem
Description
LeetCode Problem 1144.
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, ie.
A[0] > A[1] < A[2] > A[3] < A[4] > ... - OR, every odd-indexed element is greater than adjacent elements, ie.
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.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: We can decrease 2 to 0 or 3 to 1.
Example 2:
Input: nums = [9,6,1,6,2]
Output: 4
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 1000
Solution
Approach: Try Both Patterns, Lower Only the Valleys
A zigzag array has its "valleys" either at all even indices or at all odd indices. Try both and keep the cheaper one.
Say the valleys must be at the indices of one parity. Since moves only decrease values, there is no point touching the peaks: lowering a peak only makes it harder for its neighbors to be smaller. So the peaks keep their values, and each valley nums[j] must drop just below the smaller of its neighbors (one neighbor at the ends of the array). That costs
max(0, nums[j] - min(neighbors) + 1) moves.
Valleys are never next to each other, so lowering one does not affect another, and the total for this pattern is just the sum. The answer is the smaller of the two totals.
For example, [9, 6, 1, 6, 2]: valleys at even indices cost (9 - 6 + 1) + 0 + 0 = 4; valleys at odd indices cost 0 + (6 - 1 + 1) = 6. The answer is 4.
Complexity: O(n) time and O(1) extra space.
class Solution:
def movesToMakeZigzag(self, nums: List[int]) -> int:
n = len(nums)
cost = [0, 0] # cost[p]: moves needed so that the indices with parity p are the low points
for p in range(2):
for j in range(p, n, 2):
# nums[j] must drop below both neighbors; neighbors are never decreased.
low = min(nums[j - 1] if j > 0 else 10 ** 9, nums[j + 1] if j + 1 < n else 10 ** 9)
cost[p] += max(0, nums[j] - low + 1)
return min(cost)