-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1144decrease_elements_to_make_array_zigzag.js
More file actions
44 lines (36 loc) · 1.08 KB
/
1144decrease_elements_to_make_array_zigzag.js
File metadata and controls
44 lines (36 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/
var movesToMakeZigzag = function(nums) {
let ans1 = 0;
let ans2 = 0;
let temp = [...nums];
for (let i = 0; i < temp.length; i += 2) {
if (i - 1 >= 0) {
if (temp[i] <= temp[i - 1]) {
ans1 += temp[i - 1] - temp[i] + 1;
temp[i - 1] = temp[i] - 1;
}
}
if (i + 1 < temp.length) {
if (temp[i] <= temp[i + 1]) {
ans1 += temp[i + 1] - temp[i] + 1;
temp[i + 1] = temp[i] - 1;
}
}
}
temp = [...nums];
for (let i = 1; i < temp.length; i += 2) {
if (i - 1 >= 0) {
if (temp[i] <= temp[i - 1]) {
ans2 += temp[i - 1] - temp[i] + 1;
temp[i - 1] = temp[i] - 1;
}
}
if (i + 1 < temp.length) {
if (temp[i] <= temp[i + 1]) {
ans2 += temp[i + 1] - temp[i] + 1;
temp[i + 1] = temp[i] - 1;
}
}
}
return Math.min(ans1, ans2);
};