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.spa

Note: You may not slant the container.orm

 

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

相關文章
相關標籤/搜索