Skip to content

Commit 034d951

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <[email protected]>
1 parent e7da092 commit 034d951

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

0135_candy/candy.c

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4-
static int candy(int* ratings, int ratingsSize)
4+
5+
int candy(int* ratings, int ratingsSize)
56
{
6-
if (ratingsSize == 0) return 0;
7-
if (ratingsSize == 1) return 1;
7+
if (ratingsSize == 0) {
8+
return 0;
9+
}
810

911
int i, *candies = malloc(ratingsSize * sizeof(int));
1012
candies[0] = 1;

0135_candy/candy.cc

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
int candy(vector<int>& ratings) {
8+
vector<int> candies(ratings.size(), 1);
9+
for (int i = 1; i < ratings.size(); i++) {
10+
if (ratings[i] > ratings[i - 1]) {
11+
candies[i] = candies[i - 1] + 1;
12+
}
13+
}
14+
15+
int sum = candies[ratings.size() - 1];
16+
for (int i = ratings.size() - 2; i >= 0; i--) {
17+
if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
18+
candies[i] = candies[i + 1] + 1;
19+
}
20+
sum += candies[i];
21+
}
22+
return sum;
23+
}
24+
};

0 commit comments

Comments
 (0)