-
Notifications
You must be signed in to change notification settings - Fork 0
/
Candy.cpp
32 lines (30 loc) Β· 832 Bytes
/
Candy.cpp
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
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
int candy = n, i=1;
while(i<n){
if(ratings[i] == ratings[i-1]){
i++;
continue;
}
//For increasing slope
int peak = 0;
while(ratings[i] > ratings [i-1]){
peak++;
candy += peak;
i++;
if(i == n) return candy;
}
//For decreasing slope
int valley = 0;
while(i<n && ratings[i] < ratings[i-1]){
valley++;
candy += valley;
i++;
}
candy -= min(peak, valley); //Keep only the higher peak
}
return candy;
}
};