给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水
1. 动态规划的解法
class Solution {
public int trap(int[] height) {
if(height == null || height.length == 0) {
return 0;
}
int[] leftMax = new int[height.length];
int[] rightMax = new int[height.length];
// 计算左侧最大高度
leftMax[0] = height[0];
for(int i = 1; i < height.length; i++) {
leftMax[i] = Math.max(leftMax[i - 1], height[i]);
}
// 计算右侧最大高度
rightMax[height.length - 1] = height[height.length - 1];
for(int i = height.length - 2; i >= 0; i--) {
rightMax[i] = Math.max(rightMax[i + 1], height[i]);
}
// 计算总的积水容量
int water = 0;
for(int i = 0; i < height.length; i++) {
int waterHeight = Math.min(leftMax[i], rightMax[i]) - height[i];
if(waterHeight > 0) {
water = water + waterHeight;
}
}
return water;
}
}