LeetCode-11 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.
Note: You may not slant the container.
思路:
假设有(i,A[i]),(j,A[j])构成的容器是目前发现的最大容器S;
则i的左边一定不存在k<i && A[k]>=A[i],否则与“目前发现的最大容器”这一假设矛盾;
同理,j的右边也不存在比A[j]大的线;
那么,可能的更大的容器在位于i,j之间。
取A[i]和A[j]较小的那个往中间移动(此时小的那个是瓶颈),
1. 如果i<k<j && A[K] <= A[i],继续移动;
2. 如果i<k<j && A[K] > A[i],则可能出现更大值,此时计算当前的面积S1
3. 如果S1 > S,更新S1
4. 在(i~k)或者(k~j)之间重复执行1-4步,直到i==j.
代码如下:
public int maxArea(int[] height) {
int i = 0;
int j = height.length-1;
int max = (j-i) * Math.min(height[i], height[j]);
while(i<j) {
int k;
if(height[i] <= height[j]) {
for(k=i+1; k<j && height[k] <= height[i]; k++) {}
i = k;
} else {
for(k=j-1; k>i && height[k] <= height[j]; k--) {}
j = k;
}
max = (j-i) * Math.min(height[i], height[j]) > max ? (j-i) * Math.min(height[i], height[j]) : max;
}
return max;
}
posted on 2015-03-09 21:15 linxiong1991 阅读(106) 评论(0) 收藏 举报
浙公网安备 33010602011771号