LC42 接雨水

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);
            ans += l * fmin(w1, w2);
            top--;
        }
        stack[++top] = i;
    }
    free(stack);
    return ans;
}
原文地址:https://www.cnblogs.com/lihanwen/p/10926802.html