File tree 2 files changed +36
-0
lines changed
2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 23
23
31|[ Next Permutation] ( ./0031-next-permutation.js ) |Medium|
24
24
36|[ Valid Sudoku] ( ./0036-valid-sudoku.js ) |Medium|
25
25
41|[ First Missing Positive] ( ./0041-first-missing-positive.js ) |Hard|
26
+ 42|[ Trapping Rain Water] ( ./0042-trapping-rain-water.js ) |Hard|
26
27
43|[ Multiply Strings] ( ./0043-multiply-strings.js ) |Medium|
27
28
49|[ Group Anagrams] ( ./0049-group-anagrams.js ) |Medium|
28
29
50|[ Pow(x, n)] ( ./0050-powx-n.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 42. Trapping Rain Water
3
+ * https://leetcode.com/problems/trapping-rain-water/
4
+ * Difficulty: Hard
5
+ *
6
+ * Given `n` non-negative integers representing an elevation map where the width
7
+ * of each bar is `1`, compute how much water it can trap after raining.
8
+ */
9
+
10
+ /**
11
+ * @param {number[] } height
12
+ * @return {number }
13
+ */
14
+ var trap = function ( height ) {
15
+ const leftMax = [ ] ;
16
+ const rightMax = [ ] ;
17
+ let result = 0 ;
18
+
19
+ leftMax [ 0 ] = height [ 0 ] ;
20
+ rightMax [ height . length - 1 ] = height [ height . length - 1 ] ;
21
+
22
+ for ( let i = 1 ; i < height . length ; i ++ ) {
23
+ leftMax [ i ] = Math . max ( height [ i ] , leftMax [ i - 1 ] ) ;
24
+ }
25
+
26
+ for ( let i = height . length - 2 ; i > - 1 ; i -- ) {
27
+ rightMax [ i ] = Math . max ( height [ i ] , rightMax [ i + 1 ] ) ;
28
+ }
29
+
30
+ for ( let i = 0 ; i < height . length ; i ++ ) {
31
+ result += Math . min ( leftMax [ i ] , rightMax [ i ] ) - height [ i ] ;
32
+ }
33
+
34
+ return result ;
35
+ } ;
You can’t perform that action at this time.
0 commit comments