forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcandy.cpp
28 lines (24 loc) · 801 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
// Time Complexity: O(n)
// Space Complexity: O(n)
class Solution {
public:
int candy(vector<int> &ratings) {
const int n = ratings.size();
vector<int> increment(n, 0);
// left to right
for(int i = 1, inc = 0; i < n; ++i) {
if(ratings[i] > ratings[i - 1])
increment[i] = max(++inc, increment[i]);
else
inc = 0;
}
// right to left
for(int i = n - 2, inc = 0; i >= 0; --i) {
if(ratings[i] > ratings[i + 1])
increment[i] = max(++inc, increment[i]);
else
inc = 0;
}
return accumulate(increment.begin(), increment.end(), n);
}
};