-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.cpp
43 lines (39 loc) · 1.13 KB
/
Solution.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
33
34
35
36
37
38
39
40
41
42
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
#include <unordered_map>
#include <cmath>
#include <queue>
using namespace std;
class Solution {
public:
int candy(vector<int>& ratings) {
if (ratings.size() <= 1) return ratings.size();
int total = 1, prev = 1, countDown = 0;
for (int i = 1; i < ratings.size(); i++) {
if (ratings[i] >= ratings[i-1]) {
if (countDown > 0) {
total += countDown*(countDown+1)/2; // arithmetic progression
if (countDown >= prev) total += countDown - prev + 1;
countDown = 0;
prev = 1;
}
prev = ratings[i] == ratings[i-1] ? 1 : prev+1;
total += prev;
} else countDown++;
}
if (countDown > 0) { // if we were descending at the end
total += countDown*(countDown+1)/2;
if (countDown >= prev) total += countDown - prev + 1;
}
return total;
}
};
int main() {
Solution a;
return 0;
}