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!

分析

我们要得到每一个bar的储水量,需要知道它左右最大高度,用 min(max_left,max_right) - height(height当前bar的高度)。可以得到公式container[i] = min(max_left[i],max_right[i])-height[i]。根据这个公式我们进行两次扫描:
方法一: O(n),O(n)
1、从左到右找到左边最高的柱子。
2、从右到左 找到右边最高的柱子。
3、[0,n) 计算 总的面积。
从两边各扫描一次得到我们想要维护的变量,这个一个常用的技巧。
方法二:优化 O(n),O(1)
1、从两边往中间搜索,跟新A[0,left],A[right,n]的最大值 maxLeft和maxRight
2、如果 maxLeft<maxRight说明左边 maxLeft-A[i]的水量一定可以加入,因为右边有个更高的屏障
3、同理 则maxRiht-A[i]可以加入

复杂度:O(N), 空间需要一个长度为n的数组,复杂度也是O(N)

代码

方法一:
方法二:

参考

http://blog.csdn.net/cinderella_niu/article/details/43482897
http://www.sohu.com/a/153858619_466939 //漫画动态规划

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值