Skip to content

Commit 61ec915

Browse files
committed
Add solution #42
1 parent 9990f30 commit 61ec915

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
31|[Next Permutation](./0031-next-permutation.js)|Medium|
2424
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
2525
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|
26+
42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard|
2627
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|
2728
49|[Group Anagrams](./0049-group-anagrams.js)|Medium|
2829
50|[Pow(x, n)](./0050-powx-n.js)|Medium|

solutions/0042-trapping-rain-water.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
};

0 commit comments

Comments
 (0)