forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCandy.js
48 lines (38 loc) · 1.17 KB
/
Candy.js
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
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
const n = ratings.length;
let candies = [...Array(n)].fill(1);
let index = 0;
let copy = [ratings[0]];
let isDecreasing = true;
for(let i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
isDecreasing = false;
break;
}
/* In case of decreasing sequence, make a copy of the current rating, but in inverted format */
copy.unshift(ratings[i]);
}
if (isDecreasing) {
ratings = copy;
} else {
copy = [];
}
while(index >= 0) {
if (index >= n) {
break;
}
if (ratings[index] > ratings[index + 1] && candies[index + 1] >= candies[index]) {
candies[index] = candies[index] + 1;
index = Math.max(-1, index - 2);
}
else if (ratings[index] > ratings[index - 1] && candies[index - 1] >= candies[index]) {
candies[index] = candies[index - 1] + 1;
}
index++;
}
return candies.reduce((sum, candy) => sum + candy, 0);
}