-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0135-candy.js
More file actions
28 lines (24 loc) · 869 Bytes
/
0135-candy.js
File metadata and controls
28 lines (24 loc) · 869 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
26
27
28
/**
* Candy
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
var candy = function(ratings) {
const totalChildren = ratings.length;
const candiesGiven = new Array(totalChildren).fill(1);
for (let childIndex = 1; childIndex < totalChildren; childIndex++) {
if (ratings[childIndex] > ratings[childIndex - 1]) {
candiesGiven[childIndex] = candiesGiven[childIndex - 1] + 1;
}
}
for (let backwardIndex = totalChildren - 2; backwardIndex >= 0; backwardIndex--) {
if (ratings[backwardIndex] > ratings[backwardIndex + 1]) {
candiesGiven[backwardIndex] = Math.max(candiesGiven[backwardIndex], candiesGiven[backwardIndex + 1] + 1);
}
}
let finalCandySum = 0;
for (const individualCandy of candiesGiven) {
finalCandySum += individualCandy;
}
return finalCandySum;
};