File tree Expand file tree Collapse file tree 2 files changed +26
-18
lines changed Expand file tree Collapse file tree 2 files changed +26
-18
lines changed Original file line number Diff line number Diff line change @@ -59,17 +59,21 @@ The third child gets 1 candy because it satisfies the above two conditions.
59
59
*/
60
60
const candy = function (ratings ) {
61
61
const n = ratings .length ;
62
- const candies = new Array (n). fill ( 1 );
62
+ const allocates = Array . from ({ length : n }, () => 1 );
63
63
64
- for (let index = 0 ; index < n - 1 ; index++ ) {
65
- if (ratings[index + 1 ] <= ratings[index]) continue ;
66
- candies[index + 1 ] = candies[index] + 1 ;
64
+ for (let index = 1 ; index < n; index++ ) {
65
+ if (ratings[index] > ratings[index - 1 ]) {
66
+ allocates[index] = allocates[index - 1 ] + 1 ;
67
+ }
67
68
}
68
- for (let index = n - 1 ; index > 0 ; index-- ) {
69
- if (ratings[index - 1 ] <= ratings[index]) continue ;
70
- if (candies[index - 1 ] > candies[index]) continue ;
71
- candies[index - 1 ] = candies[index] + 1 ;
69
+
70
+ for (let index = n - 2 ; index >= 0 ; index-- ) {
71
+ if (ratings[index] <= ratings[index + 1 ]) continue ;
72
+ if (allocates[index] > allocates[index + 1 ]) continue ;
73
+
74
+ allocates[index] = allocates[index + 1 ] + 1 ;
72
75
}
73
- return candies .reduce ((result , count ) => result + count);
76
+
77
+ return allocates .reduce ((result , allocate ) => result + allocate);
74
78
};
75
79
```
Original file line number Diff line number Diff line change 4
4
*/
5
5
const candy = function ( ratings ) {
6
6
const n = ratings . length ;
7
- const candies = new Array ( n ) . fill ( 1 ) ;
7
+ const allocates = Array . from ( { length : n } , ( ) => 1 ) ;
8
8
9
- for ( let index = 0 ; index < n - 1 ; index ++ ) {
10
- if ( ratings [ index + 1 ] <= ratings [ index ] ) continue ;
11
- candies [ index + 1 ] = candies [ index ] + 1 ;
9
+ for ( let index = 1 ; index < n ; index ++ ) {
10
+ if ( ratings [ index ] > ratings [ index - 1 ] ) {
11
+ allocates [ index ] = allocates [ index - 1 ] + 1 ;
12
+ }
12
13
}
13
- for ( let index = n - 1 ; index > 0 ; index -- ) {
14
- if ( ratings [ index - 1 ] <= ratings [ index ] ) continue ;
15
- if ( candies [ index - 1 ] > candies [ index ] ) continue ;
16
- candies [ index - 1 ] = candies [ index ] + 1 ;
14
+
15
+ for ( let index = n - 2 ; index >= 0 ; index -- ) {
16
+ if ( ratings [ index ] <= ratings [ index + 1 ] ) continue ;
17
+ if ( allocates [ index ] > allocates [ index + 1 ] ) continue ;
18
+
19
+ allocates [ index ] = allocates [ index + 1 ] + 1 ;
17
20
}
18
- return candies . reduce ( ( result , count ) => result + count ) ;
21
+
22
+ return allocates . reduce ( ( result , allocate ) => result + allocate ) ;
19
23
} ;
You can’t perform that action at this time.
0 commit comments