-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsolution.js
More file actions
64 lines (50 loc) · 1.28 KB
/
solution.js
File metadata and controls
64 lines (50 loc) · 1.28 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const decreaseEven = (nums) => {
let count = 0
for (let i = 0; i < nums.length; i = i + 2) {
if (i === 0) {
if (nums[0] >= nums[1]) {
count += (nums[0] - nums[1] + 1)
}
continue
}
if (i === nums.length - 1) {
const lastIndex = nums.length - 1
if (nums[lastIndex] >= nums[lastIndex - 1]) {
count += (nums[lastIndex] - nums[lastIndex - 1] + 1)
}
continue
}
const target = (nums[i - 1] < nums[i + 1])
? nums[i - 1]
: nums[i + 1]
if (nums[i] >= target) {
count += (nums[i] - target + 1)
}
}
return count
}
const decreaseOdd = (nums) => {
let count = 0
for (let i = 1; i < nums.length; i = i + 2) {
if (i === nums.length - 1) {
const lastIndex = nums.length - 1
if (nums[lastIndex] >= nums[lastIndex - 1]) {
count += (nums[lastIndex] - nums[lastIndex - 1] + 1)
}
continue
}
const target = (nums[i - 1] < nums[i + 1])
? nums[i - 1]
: nums[i + 1]
if (nums[i] >= target) {
count += (nums[i] - target + 1)
}
}
return count
}
const movesToMakeZigzag = (nums) => {
const countEven = decreaseEven(nums)
const countOdd = decreaseOdd(nums)
return Math.min(countEven, countOdd)
}
module.exports = movesToMakeZigzag