Container With Most Water(Medium)

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.

解题思路

当从两边向中间考虑时,乘水的面积是由(两端较小的高度)×(两个板之间的宽度)决定的。

假定初始的盛水面积为ans=0,lh为左边的高度,rh为右边的高度,如果lh < rh, 则向右运动,寻找第一个比当前lh大的左节点。同理,如果lh > rh,则向左运动, 寻找第一个比当前rh大的右节点。

public int maxArea(int[] height) {
    if (height.length <= 1)
        return 0;

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

results matching ""

    No results matching ""