Container with Most Water

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.


11/3

先使left = 0, right=len-1, 注意的是如果使left向right靠近的时候容器的底边长度会减少, 如果这样做容器可以容纳更多的水, 那么移动后的那一边的高度必须变大,

另外的问题就是移动哪一条边, 以底下的为栗:

【1,2,3,3,2,4,5】

【0,1,2,3,4,5,6】

开始的时候left = 0, right = 6, 容积是6*1 = 6

这时候左边比较小, 所以把左边左移, 注意到left[1] > left[0], 所以

left = 1, right = 6, 容积是5*2 = 10

left = 2, right = 6, 容积是4*3 = 12

left = 6, right =6, 容积是4*1=4

public class Solution {
    public int maxArea(int[] H) {
        int len = H.length;
        
        int left = 0, right = len-1;
        int max_area = 0;
        while(left < right){
            int area = Math.min(H[left], H[right])*(right-left); //err1: right > left!
            if(area > max_area)     max_area = area;
            
            // move the smaller of left and right
            if(H[left] < H[right]){
                int prev = H[left++];
                while(left < right){
                    if(H[left] > prev)      break;
                    else    left++;
                }
            }else{
                int prev = H[right--];
                while(left < right){
                    if(H[right] > prev)     break;
                    else    right--;
                }
            }
            
        }
        
        return max_area;
    }
}

空间复杂度是O(1),  时间是O(n)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值