11. 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 and n is at least 2.
two pointer做出来了 但是solution简洁的多 

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

想法是这样的 假如输入是 4,2,3,1,5
盛水量是由两边中较短的一边决定的 于是 我们首先初始化两边分变为数组的起始和结束
用maxarea存当前算出的最大面积 现在是4*(5-1) = 4
接下来 该将两边向中间移动了 但是移动那边呢
因为盛水量总是由高度低的一边决定 现在我们想最大化盛水量
如果右边向左移动 分两种情况
1.移动之后 右边高度大于左边 盛水量会减少 因为宽度变小 而高度是两边中较低的那个 也就是左边 没有变化
2.移动之后 右边小于左边 盛水量会减少 因为这次宽度和高度都变小了
也就是说 如果移动高度较高的一边 盛水量一定会减少 所以我们会尝试移动高度较低的一边
这样如果左边移动之后高度变高 才有可能去抵消因为宽度变所造成的盛水量减少

也可以这样想 我们每次求得都是以高度较低的一边为左边界 所形成的空间 的最大盛水量
最终把这些值求max 也就是最大area 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值