blob: 83915b0e7bb14043646bf5786c21a5b5a3363d84 (
plain)
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
33
34
35
36
37
|
#include "leetcode.h"
class Solution {
public:
int candy(vector<int> &ratings) {
if (ratings.size() <= 1)
return ratings.size();
int ans = 0, up = 0, down = 0, oldSign = 0;
for (int i = 1; i < ratings.size(); i++) {
int newSign = ratings[i] > ratings[i - 1] ? 1
: ratings[i] < ratings[i - 1] ? -1
: 0;
if ((oldSign > 0 && newSign == 0) || (oldSign < 0 && newSign >= 0)) {
ans += helper(up) + helper(down) + max(up, down);
up = 0;
down = 0;
}
if (newSign > 0)
up++;
if (newSign < 0)
down++;
if (newSign == 0)
ans++;
oldSign = newSign;
}
ans += ramp(up) + ramp(down) + max(up, down) + 1;
}
private:
int helper(int n) { return (n * (n + 1)) / 2; }
};
int main() {
Solution obj;
vector<int> ratings = {};
cout << obj.candy(ratings);
}
|