Skip to content

Commit

Permalink
Candy
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Sep 23, 2017
1 parent 5c5b1cf commit 235a42a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 135_candy/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test candy.c
40 changes: 40 additions & 0 deletions 135_candy/candy.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>

static int candy(int* ratings, int ratingsSize)
{
if (ratingsSize == 0) return 0;
if (ratingsSize == 1) return 1;

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

for (i = 1; i < ratingsSize; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
} else {
candies[i] = 1;
}
}

int sum = candies[ratingsSize - 1];
for (i = ratingsSize - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
}
sum += candies[i];
}

return sum;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 1]);
}
printf("%d\n", candy(nums, count));
return 0;
}

0 comments on commit 235a42a

Please sign in to comment.