42. Trapping Rain Water
we need to find how many waters can each bar[i] trap. So we need to find the left peak from barto bar[i-1] and find the right peak from bar[i+1] to bar[n-1]. See the following pseudo-code:
total_water = 0;
for i = 0 to n-1:
Lmax = Max(h[0], h[1], ... h[i-1]);
Rmax = Max(h[i+1], h[i+2], ... h[n-1]);
water_and_building = Min(Lmax, Rmax); // water should not exceed the lowest height
wi = water_and_building - h[i]; // the building has some height
total_water += wi;
return total_water;