forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.cpp
More file actions
29 lines (28 loc) · 739 Bytes
/
Candy.cpp
File metadata and controls
29 lines (28 loc) · 739 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
class Solution {
public:
int candy(vector<int> &ratings) {
int n = ratings.size();
if(n<=1) {
return n;
}
vector<int> candies(n, 0);
candies[0] = 1;
for(int i=1;i<n;i++) {
candies[i-1] = max(1, candies[i-1]);
if(ratings[i]>ratings[i-1]) {
candies[i] = candies[i-1]+1;
}
}
for(int i=n-2;i>=0;i--) {
candies[i+1] = max(1, candies[i+1]);
if(ratings[i]>ratings[i+1]) {
candies[i] = max(candies[i+1]+1, candies[i]);
}
}
int sum = 0;
for(int i=0;i<n;i++) {
sum += candies[i];
}
return sum;
}
};