Given n nonnegative integer width of each column of a height map calculated Click column arrangement, it can take much rain after 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
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]) { int w1 = (top == 0 ? 0 : height[stack[top - 1]] - height[stack[top]]); int w2 = height[i] - height[stack[top]]; int l = (top == 0 ? 0 : i - stack[top - 1] - 1); years + = l * f min (w1, w2); top--; } stack[++top] = i; } free(stack); return ans; }