11. Container With Most Water

来源:互联网 发布:传奇盛世心法7升八数据 编辑:程序博客网 时间:2024/06/06 18:35

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.

木桶盛水问题,比较最左侧和最右侧的高度,哪边小就把哪边往中间移动。

如左侧是6 右侧是8 ,间距为10,此时盛水6*10;6是制约侧,如果10向中间移动水桶的有效高度不会超过6而宽度减小盛水减少,所以将6向右移动有可能出现更大值



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


0 0
原创粉丝点击