Skip to content

Commit 5341132

Browse files
authored
Merge pull request #3014 from mdmzfzl/main
Create: 0135-candy.c
2 parents 3c10ae0 + 2eb77f0 commit 5341132

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

c/0135-candy.c

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
int candy(int* ratings, int ratingsSize) {
2+
int* candies = (int*)malloc(sizeof(int) * ratingsSize);
3+
4+
// Initialize all children with 1 candy
5+
for (int i = 0; i < ratingsSize; i++) {
6+
candies[i] = 1;
7+
}
8+
9+
// First pass: from left to right
10+
for (int i = 1; i < ratingsSize; i++) {
11+
if (ratings[i] > ratings[i - 1]) {
12+
candies[i] = candies[i - 1] + 1;
13+
}
14+
}
15+
16+
// Second pass: from right to left
17+
for (int i = ratingsSize - 2; i >= 0; i--) {
18+
if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
19+
candies[i] = candies[i + 1] + 1;
20+
}
21+
}
22+
23+
// Calculate the total number of candies
24+
int totalCandies = 0;
25+
for (int i = 0; i < ratingsSize; i++) {
26+
totalCandies += candies[i];
27+
}
28+
29+
free(candies);
30+
31+
return totalCandies;
32+
}

0 commit comments

Comments
 (0)