Trapping Rain Water
Trapping Rain Water
Question : 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.
For example:
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Best Solution
|
|
Analyze : I calculated the stored water at each index a and b in my code. At the start of every loop, I update the current maximum height from left side (that is from A[0,1…a]) and the maximum height from right side(from A[b,b+1…n-1]). if(leftmax < rightmax) then, at least (leftmax-A[a]) water can definitely be stored no matter what happens between [a,b] since we know there is a barrier at the rightside(rightmax > leftmax).