forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
5c5b1cf
commit 235a42a
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test candy.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |