Container With Most Water-Leetcode OJ Problem 11

     Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.

 ∀1<=i, j<=n, 不妨令ai < aj, 则以ai和aj为边界的container所盛水的侧面积最大为A(i, j)= (j-i)*min(ai, aj) = (j-i)*ai;
此时∀1<=i<= k <=j<=n; A(i, k) = (k-i)*min(ai, ak) <= (k-i)*ai <=(j-i)*ai = A(i, j)
这就是木桶效应。

int maxArea(vector<int> &height) {
        int i=0,j=height.size()-1,result = 0;
        while(i<j){
            result = height[i]>=height[j] ? max(result,(j-i)*height[j--]) : max(result, (j-i)*height[i++]);
        }
        return result;
    }

从两端向中间搜索,比较h[i]和h[j],一旦确定哪个较小了,记录其围城的木桶盛水侧面积,然后就可以抛弃较小的h值,将其替换为另一个h值,因为此时无论怎么替换那个较大的h值,根据木桶效应,是不会增大桶的盛水量的,桶的盛水量取决于短板而不是长板的高度,只有替换掉短板,桶的盛水量才有可能增大。因此每次记录完盛水侧面积后抛弃较小的h值,并不会丢失使盛水量更大的解,从而可以省去大量不必要的搜索,令原本需要两两匹配的O(n^2)的时间复杂度降为O(n),实现复杂度也并没有提高。
 


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值