-
Notifications
You must be signed in to change notification settings - Fork 0
/
Candy.cpp
32 lines (32 loc) · 869 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();
if (N == 0) return 0;
int candy = 1, res = 1;
int maxValue = 1, maxIndex = 0;
for (int i = 1; i < N; ++i)
{
if (ratings[i] >= ratings[i-1])
{
candy = ratings[i] == ratings[i-1] ? 1 : candy + 1;
maxValue = candy;
maxIndex = i;
}
else
{
if (candy == 1) {
if (maxValue <= i - maxIndex) {
res += i - maxIndex;
maxValue++;
} else {
res += i - maxIndex - 1;
}
}
candy = 1;
}
res += candy;
}
return res;
}
};