File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments