Search This Blog

Monday, December 24, 2012

LeetCode:Container With Most Water

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.

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

No comments: