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.
11/3
先使left = 0, right=len-1, 注意的是如果使left向right靠近的时候容器的底边长度会减少, 如果这样做容器可以容纳更多的水, 那么移动后的那一边的高度必须变大,
另外的问题就是移动哪一条边, 以底下的为栗:
【1,2,3,3,2,4,5】
【0,1,2,3,4,5,6】
开始的时候left = 0, right = 6, 容积是6*1 = 6
这时候左边比较小, 所以把左边左移, 注意到left[1] > left[0], 所以
left = 1, right = 6, 容积是5*2 = 10
left = 2, right = 6, 容积是4*3 = 12
left = 6, right =6, 容积是4*1=4
public class Solution {
public int maxArea(int[] H) {
int len = H.length;
int left = 0, right = len-1;
int max_area = 0;
while(left < right){
int area = Math.min(H[left], H[right])*(right-left); //err1: right > left!
if(area > max_area) max_area = area;
// move the smaller of left and right
if(H[left] < H[right]){
int prev = H[left++];
while(left < right){
if(H[left] > prev) break;
else left++;
}
}else{
int prev = H[right--];
while(left < right){
if(H[right] > prev) break;
else right--;
}
}
}
return max_area;
}
}
空间复杂度是O(1), 时间是O(n)