File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test candy.c
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments