Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3b0be0a

Browse files
Merge pull request TheAlgorithms#527 from kgolder92/add-trapping-water
complete trapping rain water
2 parents d272b1e + d70595e commit 3b0be0a

File tree

3 files changed

+65
-2
lines changed

3 files changed

+65
-2
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @param {number[]} height
3+
* @return {number}
4+
*/
5+
6+
/* 42. Trapping Rain Water
7+
https://leetcode.com/problems/trapping-rain-water/
8+
9+
Helpful animation of this prompt: https://youtu.be/HmBbcDiJapY?t=51
10+
11+
Given n non-negative integers representing an elevation map where
12+
the width of each bar is 1, compute how much water it is able to trap
13+
after raining.
14+
15+
VIEW ELEVATION MAP ON LEETCODE
16+
17+
Example:
18+
19+
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
20+
Output: 6
21+
22+
Plan:
23+
iterate through and find left maxes
24+
iterate through and find right maxes
25+
create minheight and assign it to the min(leftmax, rightmax)
26+
if current height(element) < minheight
27+
push minheight - height into water array
28+
else
29+
push 0 onto water array
30+
31+
sum up water array and return
32+
33+
left maxes = [0,0,1,1,2,2,2,2,3,3,3,3]
34+
right maxes = [3,3,3,3,3,3,3,2,2,2,1,0]
35+
water contained = [0,0,1,0,1,2,1,0,0,1,0,0] -> sum = 6
36+
*/
37+
38+
function trap (heights) {
39+
const maxes = new Array(heights.length).fill(0)
40+
41+
let leftMax = 0
42+
for (let i = 0; i < heights.length; i++) {
43+
const height = heights[i]
44+
maxes[i] = leftMax
45+
leftMax = Math.max(leftMax, height)
46+
}
47+
48+
let rightMax = 0
49+
for (let i = heights.length - 1; i >= 0; i -= 1) {
50+
const height = heights[i]
51+
const minHeight = Math.min(rightMax, maxes[i])
52+
53+
if (height < minHeight) {
54+
maxes[i] = minHeight - height
55+
} else {
56+
maxes[i] = 0
57+
}
58+
rightMax = Math.max(rightMax, height)
59+
}
60+
return maxes.reduce((a, b) => a + b, 0)
61+
}
62+
63+
console.log(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) // -> 6

‎package-lock.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@
2727
"jest": "^26.4.2",
2828
"standard": "^14.3.4"
2929
}
30-
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /