面试题 17.21. 直方图的水量(Interview question 17.21 Water volume of histogram)

给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 1。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/volume-of-histogram-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int trap(int[] height) {
        if (height == null || height.length <= 2) {
            return 0;
        }
        int ans = 0;
        int leftMax = height[0], rightMax = height[height.length - 1];
        int left = 1, right = height.length - 2;
        while (left <= right) {
            if (leftMax < rightMax) {
                ans += Math.max(leftMax - height[left], 0);
                leftMax = Math.max(leftMax, height[left++]);
            } else {
                ans += Math.max(rightMax - height[right], 0);
                rightMax = Math.max(rightMax, height[right--]);
            }
        }
        return ans;
    }
}
————————

Given a histogram (also known as histogram), suppose someone pours water continuously from it, how much water can the histogram store in the end? The width of the histogram is 1.

Source: leetcode
Link: https://leetcode-cn.com/problems/volume-of-histogram-lcci
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

class Solution {
    public int trap(int[] height) {
        if (height == null || height.length <= 2) {
            return 0;
        }
        int ans = 0;
        int leftMax = height[0], rightMax = height[height.length - 1];
        int left = 1, right = height.length - 2;
        while (left <= right) {
            if (leftMax < rightMax) {
                ans += Math.max(leftMax - height[left], 0);
                leftMax = Math.max(leftMax, height[left++]);
            } else {
                ans += Math.max(rightMax - height[right], 0);
                rightMax = Math.max(rightMax, height[right--]);
            }
        }
        return ans;
    }
}