forked from hijiangtao/LeetCode-with-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathres.js
More file actions
25 lines (22 loc) · 594 Bytes
/
res.js
File metadata and controls
25 lines (22 loc) · 594 Bytes
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
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
const candies = ratings.map(() => 1);
const len = ratings.length;
if (len <= 1) return len;
for (let index = 1; index < len; index++) {
if (ratings[index] > ratings[index-1]) {
candies[index] = candies[index-1] + 1;
}
}
let sum = candies[len-1];
for (let index = len-2; index >= 0; index--) {
if (ratings[index] > ratings[index+1] && candies[index] <= candies[index+1]) {
candies[index] = candies[index+1] + 1;
}
sum += candies[index];
}
return sum;
};