Skip to content

Commit 08ebab3

Browse files
committed
Time: 9 ms (32.9%), Space: 57.8 MB (81.09%) - LeetHub
1 parent 4ade81a commit 08ebab3

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

0135-candy/0135-candy.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {number[]} ratings
3+
* @return {number}
4+
*/
5+
var candy = function (ratings) {
6+
const n = ratings.length;
7+
const candies = new Array(n).fill(1);
8+
9+
for (let i = 1; i < candies.length; i++) {
10+
if (ratings[i] > ratings[i - 1]) {
11+
candies[i] = candies[i - 1] + 1;
12+
}
13+
}
14+
15+
for (let i = n - 2; i >= 0; i--) {
16+
if (ratings[i] > ratings[i + 1]) {
17+
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
18+
}
19+
}
20+
21+
return candies.reduce((a, b) => a + b, 0);
22+
};

0 commit comments

Comments
 (0)