[LeetCode]011. 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.

Solution:

Use two indices(pointers)

Running time: O(n);

capacity = min(height[i], height[j]) * (j - i);

因为capacity是以最小边的高度来计算, 当固定了一条最小边(fixed)后, 另一条边在(i, j)内任意移动都不会改变此时capacity的最大值。

只能移动指向该最小边的指针,才可能改变最大值。


public class Solution {
    public int maxArea(int[] height) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int left = 0;
        int right = height.length -1;
        int mostWater = 0;
        while(left < right){
            int compacity = Math.min(height[left], height[right]) * (right - left);
            if(compacity > mostWater){
                mostWater = compacity;
            }
            if(height[left]<height[right]){
                left++;
            }else{
                right--;
            }
        }
        return mostWater;
    }
}


2015-04-08 update python solution: 解法同上,使用双指针。

class Solution:
    # @return an integer
    def maxArea(self, height):
        length = len(height)
        left = 0
        right = length - 1
        result = 0
        while left < right:
            temp = min(height[left], height[right]) * (right-left)
            if temp > result:
                result = temp
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        return result


你可能感兴趣的:(java,LeetCode,python)