84. Largest Rectangle in Histogram
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
题目大意
给出图形,计算以该图形为容器能接的雨水的最大体积。
思路
动态规划
对于每个小矩形而言,它所能装的雨水体积由其左边最大高度的矩形和右边最大高度的矩形决定,二者之间取最小值再减去自己的高度即为自己装的雨水体积。left_max[i] = max(left_max[i-1], height[i]),right_max[i] = max(right_max[i+1], height[i]),需要注意的是求左边最大值需要从左往右遍历,求右边最大值需要从右往左遍历,因为left_max[0]和right_max[l-1]是首先确定的,求的过程也分别是从左往右和从右往左进行状态转移的。最后将每个矩形能装的雨水求和即可。
单调栈
这种计算方法有点类似于计算最大矩形面积。构造一个单调递减栈,当当前矩形大于栈顶时,则说明栈顶是洼地,栈中下一个元素和当前元素都比栈顶大。我们可以计算以当前栈顶元素为最低点,栈中下一个元素和当前元素为左右边界围成的矩形的面积,其宽度是i -1-s.peek(),其高度为min(height[s.peek()], height[i]) - height[top]。之后再累积求矩形面积总和即可。
动态规划算法是算竖着的矩形面积,单调栈算的是横着的条形面积。
代码
class Solution {
public int trap(int[] height) {
int l = height.length;
if(l == 0) return 0;
int res = 0;
/**
//动态规划
int []left_max = new int[l];
int []right_max = new int[l];
left_max[0] = height[0];
right_max[l-1] = height[l-1];
for(int i = 1; i < l; i++){
left_max[i] = Math.max(left_max[i-1], height[i]);
}
for(int i = l-2; i >= 0; i--){
right_max[i] = Math.max(right_max[i+1], height[i]);
}
for(int i = 1; i < l-1; i++){
res += Math.min(left_max[i], right_max[i]) - height[i];
}
return res;
**/
//单调栈
Stack<Integer>s = new Stack<>();
for(int i = 0; i < l; i++){
while(!s.empty() && height[s.peek()] < height[i]){
int top = s.pop();
if(s.empty()) break;
int width = i - 1 - s.peek();
res += (Math.min(height[s.peek()], height[i]) - height[top])*width;
}
s.push(i);
}
return res;
}
}