# Decrease Elements To Make Array Zigzag in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums of integers, a move operation is actually choosing any element and decreasing it by 1. An array A is a zigzag array if either 1 or 2 is satisfied −

• Every even-indexed element is greater than adjacent elements, So. A > A < A > A < A > ... and so on.

• Every odd-indexed element is greater than adjacent elements, So. A < A > A < A > A < ... and so on.

We have to find the minimum number of moves to transform the given array nums into a zigzag array.

So if the array is like [1,2,3], then the output will be 2, as we can decrease 2 to 0 or 3 to 1

To solve this, we will follow these steps −

• Define a method called solve(), this will take nums and start, this will work as below −

• k := 0

• for i in range start to length of nums, increase by 2

• left := 100000 when i – 1 < 0, otherwise nums[i - 1]

• right := 100000 when i + 1 >= length of nums, otherwise nums[i + 1]

• temp := (minimum of left and right) – 1 – nums[i]

• if temp < 0, then k := k + |temp|

• return k

• In the main method, it will be

• ans := solve(nums, 0)

• ans := minimum of ans and solve(nums, 1)

• return ans

## Example

Let us see the following implementation to get better understanding −

class Solution(object):
def solve(self,nums,start):
k = 0
for i in range(start,len(nums),2):
left = 100000 if i-1<0 else nums[i-1]
right = 10000 if i+1>=len(nums) else nums[i+1]
temp= (min(left,right)-1 - nums[i])
if temp<0:
k+=abs(temp)
return k
def movesToMakeZigzag(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = self.solve(nums,0)
ans = min(ans,self.solve(nums,1))
return ans

## Input

[1,2,3]

## Output

2