題目:
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.
題意:
找到條縱線然後這兩條線以及X軸構成的容器能容納最多的水。
思路:
面積,它受長和高的影響,當長度減小時候,高必須增長才有可能提升面積,所以我們從長度最長時開始遞減,然後尋找更高的線來更新候補;
public int maxArea(int[] height) {
int left = 0;
int right = height.length-1;
int area = 0 ;
while(left<right){
area = Math.max(area, Math.min(height[left], height[right])*(right-left));
if(height[left]<height[right]){
left ++;
}
else{
right --;
}
}
return area;
}