Skip to content

Commit d79de5a

Browse files
authored
Merge pull request #258 from kaif969/feat/candy_problem
135. candy.cpp
2 parents 1089be2 + 0478eea commit d79de5a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

135. Candy.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
int candy(vector<int>& ratings) {
4+
int n = ratings.size();
5+
vector<int> count(n, 1); // Step 1: Initialize with 1
6+
7+
// Step 2: Left to Right
8+
for (int i = 1; i < n; i++) {
9+
if (ratings[i] > ratings[i - 1]) {
10+
count[i] = count[i - 1] + 1;
11+
}
12+
}
13+
14+
// Step 3: Right to Left
15+
for (int i = n - 2; i >= 0; i--) {
16+
if (ratings[i] > ratings[i + 1]) {
17+
count[i] = max(count[i], count[i + 1] + 1);
18+
}
19+
}
20+
21+
// Step 4: Total candies
22+
return accumulate(count.begin(), count.end(), 0);
23+
}
24+
};

0 commit comments

Comments
 (0)