Decrease Elements To Make Array Zigzag

Problem Id: 1144 Difficulty: Medium


Intuition

Solution


class Solution:
    def movesToMakeZigzag(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return 0

        m = max(nums)
        ans = 0
        for i in range(0, len(nums), 2):
            limit = m
            if i - 1 >= 0:
                limit = min(limit, nums[i - 1])
            if i + 1 < len(nums):
                limit = min(limit, nums[i + 1])
            if nums[i] >= limit:
                ans += nums[i] - (limit - 1)

        ans2 = 0
        for i in range(1, len(nums), 2):
            limit = m
            if i - 1 >= 0:
                limit = min(limit, nums[i - 1])
            if i + 1 < len(nums):
                limit = min(limit, nums[i + 1])
            if nums[i] >= limit:
                ans2 += nums[i] - (limit - 1)

        return min(ans, ans2)