Given n each represents a non-negative integer of 1 column width height map calculated Click column arrangement, then able to take much rain rain.
The above is an array [0,1,0,2,1,0,1,3,2,1,2,1] FIG highly represented, in this case, can take six units rainwater (blue portion represents the rain). Thank Marcos contribution to this figure.
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/trapping-rain-water
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Rainwater ha ha, using a monotonically increasing stack (the stack from the bottom to the top of the stack) the idea: When the height [i]> = height of the top element (height [stack [top]) , judgment, Note: When top> = 1:00 only make sense to compare and poor.
3 for example i =, height [3] = 2, and height [stack [top] = 0 , this case is the width of i - stack [top - 1] - 1; height min (height [i] - stack [ top], stack [top - 1 ] - stack [top]), the result ans + = w × h, and then the stack (TOP- place), and then pushed onto the stack.
int trap(int* height, int heightSize){
int ans = 0, top = -1;
int *stack = (int *)malloc(sizeof(int) * heightSize);
for (int i = 0; i < heightSize; i++) {
while (top != -1 && height[stack[top]] <= height[i]) {
if (top >= 1) {
int w = i - stack[top - 1] - 1;
int val1 = height[i] - height[stack[top]];
int val2 = height[stack[top - 1]] - height[stack[top]];
int h = (val1 < val2 ? val1 : val2);
ans += h * w;
}
top--;
}
stack[++top] = i;
}
free(stack);
return ans;
}