[LeetCode] 11. Container With Most Water

原题链接:https://leetcode.com/problems/container-with-most-water/

1. 题目介绍

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 and n is at least 2.

给出n个非负整数 a1,a2,… ,an,这些数代表了位于坐标(i,ai)处的点。从(i, 0)到(i, ai)做垂线,一共有n条这样的垂线。从这n条线中,选择两个垂线。这两条垂线和X轴形成了一个容器,为了让容器盛更多的水,需要选取最合适的两条的垂线,使得容器的容积最大。

注意:
不可以倾斜这个容器,n最小为2。
在这里插入图片描述
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
上述垂线的表示方法是数组 [1,8,6,2,5,4,8,3,7]。在这种情况下,最大容积为49

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

2. 解题思路

双指针法
本题的解题思路是双指针法。设置左边的指针left,初始位置为0,设置右边的指针right,初始位置为数组最后一个元素处。
选取height[left],height[right]中较小的一个作为高,right-left作为底边长度。因此容器的容积为:
m i n ( h e i g h t [ l e f t ] , h e i g h t [ r i g h t ] ) ∗ ( r i g h t − l e f t ) min(height[left],height[right])*(right-left) min(height[left],height[right])(rightleft)
从上述公式我们可以看出,高度和底边长度是限制容器容量的两个主要因素。
因此,需要记录下来最大的容积,然后将左右指针向中心进一步缩小。如果缩小后的最大容积超过了原来的最大容积,那么就更新最大容积的值。

如何将左右指针向中心进一步缩小呢?答案谁的height较小,就改变谁。height[left]较小,left就要右移,height[right]较小,就将right左移。

实现代码

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

3. 参考资料

https://leetcode.com/problems/container-with-most-water/solution/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值