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
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Intuition
\nDo as directed in question. For each element in the array, we find the maximum level of water it can trap after the rain, which is equal to the minimum of maximum height of bars on both the sides minus its own height.
\nAlgorithm
\nComplexity Analysis
\nTime complexity: . For each element of array, we iterate the left and right parts.
\nSpace complexity: extra space.
\nIntuition
\nIn brute force, we iterate over the left and right parts again and again just to find the highest bar size upto that index. But, this could be stored. Voila, dynamic programming.
\nThe concept is illustrated as shown:
\nAlgorithm
\nComplexity analysis
\nWe finally update using the stored values in O(n).
\nSpace complexity: extra space.
\nIntuition
\nInstead of storing the largest bar upto an index as in Approach #2, we can use stack to keep track of the bars that are bounded by longer bars and hence, may store water. Using the stack, we can do the calculations in only one iteration.
\nWe keep a stack and iterate over the array. We add the index of the bar to the stack if bar is smaller than or equal to the bar at top of stack, which means that the current bar is bounded by the previous bar in the stack. If we found a bar longer than that at the top, we are sure that the bar at the top of the stack is bounded by the current bar and a previous bar in the stack, hence, we can pop it and add resulting trapped water to .
\nAlgorithm
\nComplexity analysis
\nIntuition\nAs in Approach #2, instead of computing the left and right parts seperately, we may think of some way to do it in one iteration.\nFrom the figure in dynamic programming approach, notice that as long as (from element 0 to 6), the water trapped depends upon the left_max, and similar is the case when (from element 8 to 11).\nSo, we can say that if there is a larger bar at one end(say right), we are assured that the water trapped would be dependant on height of bar in current direction(from left to right). As soon as we find the bar at other end(right) is smaller, we start iterating in opposite direction(from right to left).\nWe must maintain and during the iteration, but now we can do it in one iteration using 2 pointers, switching between the two.
\nAlgorithm
\nRefer the example for better understanding:\n!?!../Documents/42_trapping_rain_water.json:1000,662!?!
\n\nComplexity analysis
\nAnalysis written by @abhinavbansal0.
\n