Skip to content

Commit 235a42a

Browse files
Candy
Signed-off-by: begeekmyfriend <[email protected]>
1 parent 5c5b1cf commit 235a42a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

135_candy/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test candy.c

135_candy/candy.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static int candy(int* ratings, int ratingsSize)
5+
{
6+
if (ratingsSize == 0) return 0;
7+
if (ratingsSize == 1) return 1;
8+
9+
int i, *candies = malloc(ratingsSize * sizeof(int));
10+
candies[0] = 1;
11+
12+
for (i = 1; i < ratingsSize; i++) {
13+
if (ratings[i] > ratings[i - 1]) {
14+
candies[i] = candies[i - 1] + 1;
15+
} else {
16+
candies[i] = 1;
17+
}
18+
}
19+
20+
int sum = candies[ratingsSize - 1];
21+
for (i = ratingsSize - 2; i >= 0; i--) {
22+
if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
23+
candies[i] = candies[i + 1] + 1;
24+
}
25+
sum += candies[i];
26+
}
27+
28+
return sum;
29+
}
30+
31+
int main(int argc, char **argv)
32+
{
33+
int i, count = argc - 1;
34+
int *nums = malloc(count * sizeof(int));
35+
for (i = 0; i < count; i++) {
36+
nums[i] = atoi(argv[i + 1]);
37+
}
38+
printf("%d\n", candy(nums, count));
39+
return 0;
40+
}

0 commit comments

Comments
 (0)