-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcandy.js
More file actions
35 lines (34 loc) · 904 Bytes
/
candy.js
File metadata and controls
35 lines (34 loc) · 904 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
29
30
31
32
33
34
35
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
var prev = 1;
var latestLocalMaxIndex = 0;
var latestLocalMaxValue = 1;
var results = 1;
for (var i = 1; i < ratings.length; i++){
if (ratings[i] < ratings[i-1]){
// Case 1 : rating is lower than previous value
if (i - latestLocalMaxIndex >= latestLocalMaxValue){
results += i - latestLocalMaxIndex + 1;
}else {
results += i - latestLocalMaxIndex;
}
prev = 1;
}else if (ratings[i] > ratings[i-1]){
// Case 2 : rating is higher than previous value
prev++;
results += prev;
latestLocalMaxValue = prev;
latestLocalMaxIndex = i;
}else {
// Case 3 : rating is equal to previous value
latestLocalMaxIndex = i;
latestLocalMaxValue = 1;
prev = 1;
results += prev;
}
}
return results;
};