Candy LeetCode solution in JavaScript

1
/**
2
* @param {number[]} ratings
3
* @return {number}
4
*/
5
var candy = function (ratings) {
6
const n = ratings.length;
7

8
let candies = [...Array(n)].fill(1);
9

10
let index = 0;
11
let copy = [ratings[0]];
12

13
let isDecreasing = true;
14
for (let i = 1; i < n; i++) {
15
if (ratings[i] > ratings[i - 1]) {
16
isDecreasing = false;
17
break;
18
}
19
/* In case of decreasing sequence, make a copy of the current rating, but in inverted format */
20
copy.unshift(ratings[i]);
21
}
22

23
if (isDecreasing) {
24
ratings = copy;
25
} else {
26
copy = [];
27
}
28

29
while (index >= 0) {
30
if (index >= n) {
31
break;
32
}
33

34
if (
35
ratings[index] > ratings[index + 1] &&
36
candies[index + 1] >= candies[index]
37
) {
38
candies[index] = candies[index] + 1;
39
index = Math.max(-1, index - 2);
40
} else if (
41
ratings[index] > ratings[index - 1] &&
42
candies[index - 1] >= candies[index]
43
) {
44
candies[index] = candies[index - 1] + 1;
45
}
46

47
index++;
48
}
49

50
return candies.reduce((sum, candy) => sum + candy, 0);
51
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0