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
方法
一开始暴力解,结果超时了,实际上该问题有O(n)的解法。设定两个收尾指针i,j进行扫描,若height[i] <= height[j], i++
,若height[i] > height[j], j--
为什么这样就可以判断了呢,leetcode discuss里好多用的反证法,自己可以 点击 去看。
网上还有一种比较直观的解释,就是i到j-1的容积,i到j-2]的容积,不可能比i到j的容积大,因为宽不可能大于j-i,而且高度受限于height[i]
public class Solution {
public int maxArea(int[] height) {
int max = 0;
int start = 0;
int end = height.length-1;
while(start < end){
max = Math.max(max,Math.abs(Math.min(height[start],height[end]))*(end-start));
if(height[start] <= height[end]){
start++;
}else{
end--;
}
}
return max;
}
}