11. Container With Most Water

    xiaoxiao2025-03-25  14

    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; } }

    转载请注明原文地址: https://ju.6miu.com/read-1297379.html
    最新回复(0)