Decrease Elements To Make Array Zigzag LeetCode solution in Java

1
class Solution {
2
/*
3
firstly, check elements in odd indices are greater than its neighbours.
4
if not, decrease its neigbours and update the cost.
5

6
do same thing for even indices, because there can be two combinations as indicated in question.
7
*/
8

9
private int calculateCost(int[] nums, int start) {
10
int res = 0;
11
int n = nums.length;
12
int[] arr = Arrays.copyOf(nums, nums.length); // nums array will be modified, so copy it.
13

14
for (int i = start; i < n; i += 2) {
15
int prev = (i == 0) ? Integer.MIN_VALUE : arr[i - 1];
16
int cur = arr[i];
17
int next = (i == n - 1) ? Integer.MIN_VALUE : arr[i + 1];
18

19
if (prev < cur && next < cur) continue;
20

21
if (prev >= cur) {
22
res += prev - cur + 1;
23
arr[i - 1] = cur - 1;
24
}
25

26
if (next >= cur) {
27
res += next - cur + 1;
28
arr[i + 1] = cur - 1;
29
}
30
}
31
return res;
32
}
33

34
public int movesToMakeZigzag(int[] nums) {
35
return Math.min(calculateCost(nums, 0), calculateCost(nums, 1));
36
}
37
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0