File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ There are N children standing in a line. Each child is assigned a rating value.
3
+
4
+ You are giving candies to these children subjected to the following requirements:
5
+
6
+ Each child must have at least one candy.
7
+ Children with a higher rating get more candies than their neighbors.
8
+ What is the minimum candies you must give?
9
+ */
10
+
11
+ //TLE
12
+ /**
13
+ * @param {number[] } ratings
14
+ * @return {number }
15
+ */
16
+ var candy = function ( ratings ) {
17
+ let len = ratings . length ;
18
+ let candies = [ ] ;
19
+ let sum = 1 ;
20
+
21
+ candies [ 0 ] = 1 ;
22
+
23
+ for ( let i = 1 ; i < len ; i ++ ) {
24
+ if ( ratings [ i ] <= ratings [ i - 1 ] ) {
25
+ if ( candies [ i - 1 ] > 1 ) {
26
+ candies [ i ] = 1 ;
27
+ sum ++ ;
28
+ } else {
29
+ candies [ i ] = 1 ;
30
+ sum ++ ;
31
+ let k = i ;
32
+
33
+ while ( k > 0 && ( ratings [ k ] < ratings [ k - 1 ] ) && ( candies [ k - 1 ] <= candies [ k ] ) ) {
34
+ candies [ k - 1 ] ++ ;
35
+ sum ++ ;
36
+ k -- ;
37
+ }
38
+
39
+
40
+ }
41
+ } else {
42
+ candies [ i ] = candies [ i - 1 ] + 1 ;
43
+ sum += candies [ i ] ;
44
+ }
45
+ }
46
+
47
+ return sum ;
48
+ } ;
You can’t perform that action at this time.
0 commit comments