File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change 80
80
128|[ Longest Consecutive Sequence] ( ./0128-longest-consecutive-sequence.js ) |Medium|
81
81
133|[ Clone Graph] ( ./0133-clone-graph.js ) |Medium|
82
82
134|[ Gas Station] ( ./0134-gas-station.js ) |Medium|
83
+ 135|[ Candy] ( ./0135-candy.js ) |Hard|
83
84
136|[ Single Number] ( ./0136-single-number.js ) |Easy|
84
85
141|[ Linked List Cycle] ( ./0141-linked-list-cycle.js ) |Easy|
85
86
142|[ Linked List Cycle II] ( ./0142-linked-list-cycle-ii.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 135. Candy
3
+ * https://leetcode.com/problems/candy/
4
+ * Difficulty: Hard
5
+ *
6
+ * There are n children standing in a line. Each child is assigned a rating value given
7
+ * in the integer array ratings.
8
+ *
9
+ * You are giving candies to these children subjected to the following requirements:
10
+ * - Each child must have at least one candy.
11
+ * - Children with a higher rating get more candies than their neighbors.
12
+ *
13
+ * Return the minimum number of candies you need to have to distribute the candies to
14
+ * the children.
15
+ */
16
+
17
+ /**
18
+ * @param {number[] } ratings
19
+ * @return {number }
20
+ */
21
+ var candy = function ( ratings ) {
22
+ const data = new Array ( ratings . length ) . fill ( 1 ) ;
23
+
24
+ for ( let i = 1 ; i < ratings . length ; i ++ ) {
25
+ if ( ratings [ i - 1 ] < ratings [ i ] ) {
26
+ data [ i ] = data [ i - 1 ] + 1 ;
27
+ }
28
+ }
29
+
30
+ for ( let i = ratings . length - 1 ; i > 0 ; i -- ) {
31
+ if ( ratings [ i - 1 ] > ratings [ i ] ) {
32
+ data [ i - 1 ] = data [ i - 1 ] > data [ i ] + 1 ? data [ i - 1 ] : data [ i ] + 1 ;
33
+ }
34
+ }
35
+
36
+ return data . reduce ( ( sum , n ) => sum + n , 0 ) ;
37
+ } ;
You can’t perform that action at this time.
0 commit comments