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) {
    if(height == null || height.length < 2) return 0;
    int l = 0;
    int r = height.length-1;
    int area = (r-l)*Math.min(height[l], height[r]);
    while(r > l){
      if(height[l] <= height[r]){
        l++;
        if(height[l] > height[l-1]){
          area = Math.max(area, (r-l)*Math.min(height[l], height[r]));
        }
      }
      else{
        r--;
        if(height[r] > height[r+1]){
          area = Math.max(area, (r-l)*Math.min(height[l], height[r]));
        }
      }
    }
  return area;
  }
}

posted @ 2014-04-02 19:55  boole  阅读(112)  评论(0)    收藏  举报