Given an elevation map as bar heights, compute how much rain water is trapped between the bars after it rains.
Input
Line 1: an integer n.
Line 2: n non-negative integers, the bar heights.
Output
The total units of trapped water.
Given an elevation map as bar heights, compute how much rain water is trapped between the bars after it rains.
Line 1: an integer n.
Line 2: n non-negative integers, the bar heights.
The total units of trapped water.
Example 1
12 0 1 0 2 1 0 1 3 2 1 2 1
6
The classic map traps 6 units.
Example 2
6 4 2 0 3 2 5
9
Traps 9 units.
Example 3
3 1 2 3
0
Strictly increasing — nothing is trapped.
Water above a bar is limited by the shorter of the tallest bar to its left and the tallest to its right.
Two pointers from both ends, tracking the running left-max and right-max, computes this in one pass.
Two pointers with running leftMax/rightMax. Advance from the side with the smaller current height, adding (max on that side − current height) as trapped water.
import sys
d = list(map(int, sys.stdin.read().split()))
n = d[0]
h = d[1:1 + n]
lo, hi = 0, n - 1
lm, rm, water = 0, 0, 0
while lo < hi:
if h[lo] < h[hi]:
if h[lo] >= lm:
lm = h[lo]
else:
water += lm - h[lo]
lo += 1
else:
if h[hi] >= rm:
rm = h[hi]
else:
water += rm - h[hi]
hi -= 1
print(water)
Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.