Trapping Rain Water Java

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!

Have you been asked this question in an interview? 


 Key to Solve: DP + corrected formula
    Idea: create two arrays in size of A.length, then scan for twice
    1. scan from left to right: record highest pointer from left-side
    2. scan from right to left: record highest pointer from right-side
    3. count in formula of volume = min(left[i],right[i])-A[i];
Check for coding in detail below:

   
public class Solution {
    public int trap(int[] A) {
          //check for special case
        if(A==null || A.length==0) return 0;
        int len=A.length;
        int water=0;
        int maxLeft=0, maxRight=0;
        int[] left=new int[len];
        int[] right=new int[len];
        //from left -> right
        for(int i=0;i<len;i++){
            left[i]=maxLeft;
            maxLeft=Math.max(maxLeft,A[i]);
        }
        //from right -> left
        for(int i=len-1;i>=0;i--){
            right[i]=maxRight;
            maxRight=Math.max(maxRight,A[i]);
        }
        //count trapped water
        for(int i=0;i<len;i++){
            int volume =Math.min(left[i],right[i])-A[i];
            if(volume>0) water+=volume;
        }
        return water;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值