-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
36 lines (33 loc) · 930 Bytes
/
Copy pathsolution.cpp
File metadata and controls
36 lines (33 loc) · 930 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
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
int minCandy(vector<int>& arr) {
int n = arr.size();
if (n == 0) return 0;
long long total = 1; // first child gets 1 candy
int up = 0, down = 0, peak = 0;
for (int i = 1; i < n; i++) {
// Increasing slope
if (arr[i] > arr[i - 1]) {
up++;
peak = up;
down = 0;
total += 1 + up;
}
// Equal ratings
else if (arr[i] == arr[i - 1]) {
up = down = peak = 0;
total += 1;
}
// Decreasing slope
else {
down++;
up = 0;
total += 1 + down;
if (down <= peak) {
total--; // adjust peak
}
}
}
return total;
}
};