File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Linear
3+ * Time O(n) | Space O(n)
4+ * https://leetcode.com/problems/trapping-rain-water
5+ * @param {number[] } height
6+ * @return {number }
7+ *
8+ */
9+ var trap = function ( height ) {
10+
11+ const maxLeft = [ ] ;
12+ const maxRight = [ ] ;
13+ const minLeftRight = [ ] ;
14+
15+ let current = 0 ;
16+ for ( let i = 0 ; i < height . length ; i ++ ) {
17+ maxLeft . push ( current ) ;
18+ current = Math . max ( current , height [ i ] ) ;
19+ }
20+ current = 0 ;
21+ for ( let i = height . length - 1 ; i > - 1 ; i -- ) {
22+ maxRight . push ( current ) ;
23+ current = Math . max ( current , height [ i ] ) ;
24+ }
25+ // because the elements were added reverse.
26+ maxRight . reverse ( ) ;
27+
28+ for ( let i = 0 ; i < height . length ; i ++ ) {
29+ const minofLeftRight = Math . min ( maxLeft [ i ] , maxRight [ i ] ) ;
30+ minLeftRight . push ( minofLeftRight ) ;
31+ }
32+
33+ let water = 0 ;
34+ for ( let i = 0 ; i < height . length ; i ++ ) {
35+ if ( minLeftRight [ i ] - height [ i ] > 0 ) {
36+ water += minLeftRight [ i ] - height [ i ] ;
37+ }
38+ }
39+
40+ return water ;
41+ } ;
42+
43+
144/**
245 * https://leetcode.com/problems/trapping-rain-water/
346 * Time O(N) | Space O(1)
You can’t perform that action at this time.
0 commit comments