LeetCode:Container With Most Water

Container With Most Water




Total Accepted: 80614  Total Submissions: 230716  Difficulty: Medium

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two 

endpoints of line i is at (iai) 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.

Subscribe to see which companies asked this question

Hide Tags
  Array Two Pointers
Hide Similar Problems
  (H) Trapping Rain Water



















思路:

先看代码,然后看证明。

证明:

反证法:假如我们得到的结果不是最优的,那必定有一个比我们更好的结果,他的左右横坐标分别为a_la_r

因为我们的循环直到两根指针相遇才结束,也就是说我们必定在某个时刻有一个指针指向了a_l或者a_r但是没有同时指向他们。不失一般性的,假设在这个时刻,我们指向了a_l,但没指向a_r,此时a_l有以下两种情况会发生变化:

  1. a_l在循环退出前没移动过。high指针一直向a_l靠拢,直到他们相遇。这个时候循环退出,但是high指针在向a_l靠拢时必定指向过a_r,这与前提矛盾。(只要high指针经历过a_r那么便会记录并得到这个假设的最优解)。 
  2. a_l指针移动了。此时high指针在指向a_r之前一定得到过比a_l指的值更大的值,这个时候a_l就会向右移动了。可是我们要知道,当前的a_l和high指针组成的容器要比所谓的最优解(a_la_r组成的容器)更高更宽,这与a_la_r是最优解矛盾。 

所有情况都矛盾,得证。


java code:

public class Solution {
    public int maxArea(int[] height) {
        
        int maxArea = 0;
        int lo = 0;
        int hi = height.length-1;
        while(lo < hi) {
            maxArea = Math.max(maxArea, (hi-lo) * Math.min(height[lo], height[hi]));
            if(height[lo] < height[hi])
                lo++;
            else
                hi--;
        }
        return maxArea;
    }
}


参考:https://leetcode.com/discuss/1074/anyone-who-has-a-o-n-algorithm


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值