Decrease Elements To Make Array Zigzag LeetCode solution in Python

1
class Solution:
2
def solve(self, arr, n, x):
3
idx = 1
4
ans = 0
5
while idx < n:
6
if idx == 0:
7
idx += 1
8
if idx % 2 == x:
9
if arr[idx - 1] >= arr[idx]:
10
ans += arr[idx - 1] - arr[idx] + 1
11
arr[idx - 1] = arr[idx] - 1
12
idx = idx - 1
13
else:
14
idx = idx + 1
15
else:
16
if arr[idx - 1] <= arr[idx]:
17
ans += arr[idx] - arr[idx - 1] + 1
18
arr[idx] = arr[idx - 1] - 1
19
idx += 1
20
return ans
21

22
def movesToMakeZigzag(self, nums: List[int]) -> int:
23
ans1 = self.solve([x for x in nums], len(nums), 0)
24
ans2 = self.solve([x for x in nums], len(nums), 1)
25
return min(ans1, ans2)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0