-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathcandy.cpp
More file actions
24 lines (23 loc) · 700 Bytes
/
candy.cpp
File metadata and controls
24 lines (23 loc) · 700 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
// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param ratings Children's ratings
* @return the minimum candies you must give
*/
int candy(vector<int>& ratings) {
vector<int> candies(ratings.size(), 1);
for (int i = 1; i < ratings.size(); ++i) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
for (int i = ratings.size() - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
}
}
return accumulate(candies.cbegin(), candies.cend(), 0);
}
};