-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy path135. Candy.cpp
More file actions
24 lines (21 loc) · 655 Bytes
/
135. Candy.cpp
File metadata and controls
24 lines (21 loc) · 655 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
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> count(n, 1); // Step 1: Initialize with 1
// Step 2: Left to Right
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
count[i] = count[i - 1] + 1;
}
}
// Step 3: Right to Left
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
count[i] = max(count[i], count[i + 1] + 1);
}
}
// Step 4: Total candies
return accumulate(count.begin(), count.end(), 0);
}
};