Skip to content

Commit e3c875d

Browse files
committed
Create Candy.cc
Add Candy.
1 parent e055084 commit e3c875d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Candy.cc

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
int candy(vector<int> &ratings) {
4+
// Note: The Solution object is instantiated only once and is reused by each test case.
5+
int ret = 0;
6+
if (ratings.size() == 0)
7+
return ret;
8+
vector<int> dp(ratings.size(), 1);
9+
for (int i = 1; i < ratings.size(); i++)
10+
if (ratings[i] > ratings[i - 1])
11+
dp[i] = dp[i - 1] + 1;
12+
13+
ret = dp[ratings.size() - 1];
14+
for (int i = ratings.size() - 2; i >= 0; i--) {
15+
if (ratings[i] > ratings[i + 1]) {
16+
dp[i] = max(dp[i], dp[i + 1] + 1);
17+
}
18+
ret += dp[i];
19+
}
20+
return ret;
21+
}
22+
};

0 commit comments

Comments
 (0)