forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcandy(AC).cpp
More file actions
29 lines (29 loc) · 735 Bytes
/
candy(AC).cpp
File metadata and controls
29 lines (29 loc) · 735 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
// O(n) time and space. How to reach O(1) space?
class Solution {
public:
/**
* @param ratings Children's ratings
* @return the minimum candies you must give
*/
int candy(vector<int> &ratings) {
vector<int> &a = ratings;
int n = a.size();
vector<int> c(n, 1);
int i;
for (i = 1; i <= n - 1; ++i) {
if (a[i] > a[i - 1]) {
c[i] = c[i - 1] + 1;
}
}
for (i = n - 2; i >= 0; --i) {
if (a[i] > a[i + 1] && c[i] <= c[i + 1]) {
c[i] = c[i + 1] + 1;
}
}
int sum = 0;
for (i = 0; i <= n - 1; ++i) {
sum += c[i];
}
return sum;
}
};