Trapping Rain Water

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.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.


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!

public class Solution {
    public int trap(int[] height) {
        int sum = 0;
        int pre;
        int maxIndex = -1;
        int max = -1;
        for(int i = 0; i < height.length; i++){
            if(height[i] > max){
                max = height[i];
                maxIndex = i;
            }
        }
        pre = 0;
        for(int i = 0; i < maxIndex; i++){
            if(height[i] > pre){
                sum += (height[i] - pre)*(maxIndex - i);
                pre = height[i];
            }
            sum -= height[i];
        }
        pre = 0;
        for(int i = height.length-1; i> maxIndex; i--){
            if(height[i] > pre){
                sum += (height[i] - pre)*(i - maxIndex);
                pre = height[i];
            }
            sum -= height[i];
        }
        return sum;
    }
}



sum = sum + (maxIndex - i )*(height[i] - pre) , 记录的是位置i时,所能存储的水量,之后在减去A[i]占据的空间,即是所能存存储的水量,比方maxIndex = 7, i = 1是,能存的水量是5,因为这时3到7之间都是空的,i = 3时,height[3] - pre = 1, 这指的是,板子变高了,高的那一部分多存的水量,应该是(2 - 1) * (7 - 3) = 4 , 再加上原来的sum = 5 就是现在的sum,之后减去height[3],即减去height[3]所占空间,得到的就是能存的水量,之后i= 4,5,6都没有i =2 高,所以能多存的水不再增加,减掉它们所占据的空间,就是左半边最终能存储的水量;右半边和左半边一样。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值