11. 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 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     }

 

posted @ 2017-10-16 07:53  daniel456  阅读(112)  评论(0编辑  收藏  举报