力扣 接雨水
public class 接雨水
{
public static int trap(int[] height)
{
int res = 0;
int len = height.length;
int[] maxLeft = new int[len];//存 i 左边最高的高度
int[] maxRight = new int[len];//存 i 右边最高的高度
maxLeft[0] = 0;
maxRight[len - 1] = 0;
// DP
for (int i = 1; i < len; i++)
maxLeft[i] = Math.max(height[i - 1], maxLeft[i - 1]);
for (int i = len - 2; i > 0; i--)
maxRight[i] = Math.max(height[i + 1], maxRight[i + 1]);
for (int i = 1; i < len - 1; i++)// 注意:第一块和最后一块无需处理,因为不会积水
{
int min = Math.min(maxLeft[i], maxRight[i]);
if (min > height[i])
res += min - height[i];
}
return res;
}
public static void main(String[] args)
{
int[] a = { 4, 2, 0, 3, 2, 5 };
int res = trap(a);
System.err.print(res);
}
}