Container With Most Water
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.
Example
Given [1,3,2]
, the max area of the container is 2
.
Note
You may not slant the container.
从数组两头遍历,计算面积,然后从小的那一段a开始找到下一个比a大的元素。直到所有数组都被遍历。
public class Solution {
/**
* @param heights: an array of integers
* @return: an integer
*/
public int maxArea(int[] heights) {
int l = heights.length;
if (l == 0) {
return 0;
}
int max = -1;
int i = 0;
int j = l-1;
while (i < j) {
int v = (j - i) * Math.min(heights[i],heights[j]);
if (max < v) {
max = v;
} if(heights[i] > heights[j]){
int x = heights[j];
while (heights[j] <= x && i < j) j--;
}else {
int x = heights[i];
while(heights[i] <= x && i < j) i++;
}
}
return max;
}
}