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 linei 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.
思路:(j-i)*Math.min(height[i],height[j]); Since i is lower than j, so there will be no jj < j that make the area from i,jj is greater than area from i,j. so the maximum area that can benefit from i is already recorded.thus, we move i forward. 这个思路很巧妙。O(N)
class Solution {
public int maxArea(int[] height) {
if(height == null || height.length == 0) {
return 0;
}
int i = 0; int j = height.length - 1;
int maxres = 0;
while(i < j) {
maxres = Math.max(maxres, (j - i) * Math.min(height[i], height[j]));
if(height[i] < height[j]) {
i++;
} else {
// height[i] > height[j];
j--;
}
}
return maxres;
}
}