Skip to content

Commit bf082a7

Browse files
committed
feat: add Trapping Rain Water
1 parent 3bfe9a0 commit bf082a7

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ https://neetcode.io/roadmap
1919
| 167 | [Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | Medium | [TypeScript](./TypeScript/167.two-sum-ii-input-array-is-sorted.ts) | Two Pointers |
2020
| 15 | [3Sum](https://leetcode.com/problems/3sum/) | Medium | [TypeScript](./TypeScript/15.3sum.ts) | Two Pointers |
2121
| 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | Medium | [TypeScript](./TypeScript/11.container-with-most-water.ts) | Two Pointers |
22+
| 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | Hard | [TypeScript](./TypeScript/42.trapping-rain-water.ts) | Two Pointers |

TypeScript/42.trapping-rain-water.ts

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
function trap(height: number[]): number {
2+
const maxLeft = new Array(height.length).fill(0);
3+
const maxRight = new Array(height.length).fill(0);
4+
5+
for (let i = 1; i < height.length; i++) {
6+
maxLeft[i] = Math.max(maxLeft[i - 1], height[i - 1]);
7+
}
8+
for (let i = height.length - 2; i >= 0; i--) {
9+
maxRight[i] = Math.max(maxRight[i + 1], height[i + 1]);
10+
}
11+
12+
return height.reduce((s, h, i) => {
13+
const v = Math.min(maxLeft[i], maxRight[i]) - h;
14+
return v > 0 ? s + v : s;
15+
}, 0);
16+
}
17+
18+
function trap2(height: number[]): number {
19+
let l = 0;
20+
let r = height.length - 1;
21+
let ml = height[l];
22+
let mr = height[r];
23+
let s = 0;
24+
25+
while (l < r) {
26+
if (ml < mr) {
27+
l++;
28+
ml = Math.max(ml, height[l]);
29+
s += ml - height[l];
30+
} else {
31+
r--;
32+
mr = Math.max(mr, height[r]);
33+
s += mr - height[r];
34+
}
35+
}
36+
37+
return s;
38+
}

0 commit comments

Comments
 (0)