Skip to content

Commit df44a1e

Browse files
authored
Create Candy.js
1 parent a8d80aa commit df44a1e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Candy.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
There are N children standing in a line. Each child is assigned a rating value.
3+
4+
You are giving candies to these children subjected to the following requirements:
5+
6+
Each child must have at least one candy.
7+
Children with a higher rating get more candies than their neighbors.
8+
What is the minimum candies you must give?
9+
*/
10+
11+
//TLE
12+
/**
13+
* @param {number[]} ratings
14+
* @return {number}
15+
*/
16+
var candy = function(ratings) {
17+
let len = ratings.length;
18+
let candies = [];
19+
let sum = 1;
20+
21+
candies[0] = 1;
22+
23+
for (let i = 1; i < len; i++) {
24+
if (ratings[i] <= ratings[i - 1]) {
25+
if (candies[i - 1] > 1) {
26+
candies[i] = 1;
27+
sum++;
28+
} else {
29+
candies[i] = 1;
30+
sum++;
31+
let k = i;
32+
33+
while (k > 0 && (ratings[k] < ratings[k - 1]) && (candies[k - 1] <= candies[k])) {
34+
candies[k - 1]++;
35+
sum++;
36+
k--;
37+
}
38+
39+
40+
}
41+
} else {
42+
candies[i] = candies[i - 1] + 1;
43+
sum += candies[i];
44+
}
45+
}
46+
47+
return sum;
48+
};

0 commit comments

Comments
 (0)