File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } h
3+ * @return {number }
4+ */
5+ var trap = function ( h ) {
6+ const n = h . length ;
7+ if ( n === 0 ) return 0 ;
8+
9+ const leftMax = new Array ( n ) . fill ( 0 ) ;
10+ const rightMax = new Array ( n ) . fill ( 0 ) ;
11+
12+ leftMax [ 0 ] = h [ 0 ] ;
13+ for ( let i = 1 ; i < n ; i ++ ) {
14+ leftMax [ i ] = Math . max ( leftMax [ i - 1 ] , h [ i ] ) ;
15+ }
16+
17+ rightMax [ n - 1 ] = h [ n - 1 ] ;
18+ for ( let i = n - 2 ; i >= 0 ; i -- ) {
19+ rightMax [ i ] = Math . max ( rightMax [ i + 1 ] , h [ i ] ) ;
20+ }
21+
22+ let totalWater = 0 ;
23+ for ( let i = 0 ; i < n ; i ++ ) {
24+ totalWater += Math . min ( leftMax [ i ] , rightMax [ i ] ) - h [ i ] ;
25+ }
26+
27+ return totalWater ;
28+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } ratings
3+ * @return {number }
4+ */
5+ var candy = function ( ratings ) {
6+ const n = ratings . length ;
7+ const ans = new Array ( n ) . fill ( 1 ) ;
8+
9+ for ( let i = 1 ; i < n ; i ++ ) {
10+ if ( ratings [ i ] > ratings [ i - 1 ] ) {
11+ ans [ i ] = ans [ i - 1 ] + 1 ;
12+ }
13+ }
14+
15+ for ( let i = n - 2 ; i >= 0 ; i -- ) {
16+ if ( ratings [ i ] > ratings [ i + 1 ] ) {
17+ ans [ i ] = Math . max ( ans [ i ] , ans [ i + 1 ] + 1 ) ;
18+ }
19+ }
20+
21+ return ans . reduce ( ( a , b ) => a + b , 0 ) ;
22+ } ;
You can’t perform that action at this time.
0 commit comments