Skip to content

Commit b1446b1

Browse files
authored
Create 0135-candy.js
1 parent e650410 commit b1446b1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

javascript/0135-candy.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Array
3+
* Time O(n) | Space O(n)
4+
* https://leetcode.com/problems/candy/
5+
* @param {number[]} ratings
6+
* @return {number}
7+
*/
8+
var candy = function(ratings) {
9+
10+
const ltr = new Array(ratings.length).fill(1);
11+
const rtl = new Array(ratings.length).fill(1);
12+
13+
// go from left to right
14+
for(let i = 1; i < ratings.length; i++) {
15+
if(ratings[i] > ratings[i-1]) {
16+
ltr[i] = ltr[i-1] + 1;
17+
}
18+
}
19+
// go from right to left
20+
for(let i = ratings.length - 2; i > -1; i--) {
21+
if(ratings[i] > ratings[i+1]) {
22+
rtl[i] = rtl[i+1] + 1;
23+
}
24+
}
25+
// calc minimum
26+
let candy = 0;
27+
for(let i = 0; i < ratings.length; i++) {
28+
candy += Math.max(ltr[i], rtl[i]);
29+
}
30+
return candy;
31+
};

0 commit comments

Comments
 (0)