-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.js
More file actions
25 lines (20 loc) · 591 Bytes
/
Candy.js
File metadata and controls
25 lines (20 loc) · 591 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
var candy = function (ratings) {
let result = new Array(ratings.length).fill(1);
// left to right
for (let i = 1; i < ratings.length; i++) {
if (ratings[i - 1] < ratings[i]) {
result[i] = result[i - 1] + 1;
}
}
// right to left
for (let i = ratings.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
result[i] = Math.max(result[i], result[i + 1] + 1);
}
}
return result.reduce((pre, curr) => pre + curr, 0);
};
const result = candy([1, 0, 2]);
console.log(result); // 5
const result1 = candy([1, 2, 2]);
console.log(result1); // 4