1. 程式人生 > >11. Container With Most Water

11. Container With Most Water

sla 其中 forms n-n 垂直 form amp pan else

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.

Note: You may not slant the container and n is at least 2.

給定n個非負整數a1,a2,...,an,其中每個代表一個點坐標(i,ai)。 n個垂直線段例如線段的兩個端點在(i,ai)和(i,0)。 找到兩個線段,與x軸形成一個容器,使其包含最多的水。 備註:你不必傾倒容器。

 1     public int maxArea(int[] height) {
 2          int max=0,left=0,right=height.length-1;
 3         while (left<height.length && right>=0 && left<right)
4 { 5 max = Math.max(max,Math.min(height[left],height[right])*(right-left)); 6 if (height[left] < height[right]) left++; 7 else right--; 8 } 9 return max; 10 }

11. Container With Most Water