给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 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;
}
}