GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — JavaScript/Dynamic-Programming/TrappingRainWater.js at master · TheAlgorithms/JavaScript

Expand file tree

/

TrappingRainWater.js

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
61 lines (48 loc) · 1.45 KB
/

TrappingRainWater.js

Copy path

File metadata and controls

61 lines (48 loc) · 1.45 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @param {number[]} height
* @return {number}
*/
/* 42. Trapping Rain Water
https://leetcode.com/problems/trapping-rain-water/
Helpful animation of this prompt: https://youtu.be/HmBbcDiJapY?t=51
Given n non-negative integers representing an elevation map where
the width of each bar is 1, compute how much water it is able to trap
after raining.
VIEW ELEVATION MAP ON LEETCODE
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Plan:
iterate through and find left maxes
iterate through and find right maxes
create minheight and assign it to the min(leftmax, rightmax)
if current height(element) < minheight
push minheight - height into water array
else
push 0 onto water array
sum up water array and return
left maxes = [0,0,1,1,2,2,2,2,3,3,3,3]
right maxes = [3,3,3,3,3,3,3,2,2,2,1,0]
water contained = [0,0,1,0,1,2,1,0,0,1,0,0] -> sum = 6
*/
export const trap = (heights) => {
const maxes = new Array(heights.length).fill(0)
let leftMax = 0
for (let i = 0; i < heights.length; i++) {
const height = heights[i]
maxes[i] = leftMax
leftMax = Math.max(leftMax, height)
}
let rightMax = 0
for (let i = heights.length - 1; i >= 0; i -= 1) {
const height = heights[i]
const minHeight = Math.min(rightMax, maxes[i])
if (height < minHeight) {
maxes[i] = minHeight - height
} else {
maxes[i] = 0
}
rightMax = Math.max(rightMax, height)
}
return maxes.reduce((a, b) => a + b, 0)
}
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.