File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 135. Candy
3
+ *
4
+ * There are N children standing in a line. Each child is assigned a rating value.
5
+ *
6
+ * You are giving candies to these children subjected to the following requirements:
7
+ *
8
+ * Each child must have at least one candy.
9
+ * Children with a higher rating get more candies than their neighbors.
10
+ * What is the minimum candies you must give?
11
+ */
12
+
13
+ /**
14
+ * @param {number[] } ratings
15
+ * @return {number }
16
+ */
17
+ var candy = function ( ratings ) {
18
+ var len = ratings . length ;
19
+ var res = [ ] ;
20
+ var sum = 0 ;
21
+ for ( var i = 0 ; i < len ; i ++ ) {
22
+ res . push ( ( i !== 0 && ratings [ i ] > ratings [ i - 1 ] ) ? ( res [ i - 1 ] + 1 ) : 1 ) ;
23
+ }
24
+ for ( var j = len - 1 ; j >= 0 ; j -- ) {
25
+ if ( j !== len - 1 && ratings [ j ] > ratings [ j + 1 ] ) res [ j ] = Math . max ( res [ j ] , res [ j + 1 ] + 1 ) ;
26
+ sum += res [ j ] ;
27
+ }
28
+ return sum ;
29
+ } ;
30
+
31
+ // 分两次循环
32
+ // 第一次从左到右,上升的依次加 1,下降或者相等的填 1
33
+ // 第二次从右到左,上升的依次加 1,下降或者相等的不管
34
+ // (注意最高点可能之前填充过,需要取 max 值,才能同时满足两边的需求)
35
+ // 第二次处理完后计算总和,省得另开一个循环
You can’t perform that action at this time.
0 commit comments