题意:给一些柱子的高度,每个柱子之间的距离是1,选两能装的水最多的柱子(无视其他柱子)。
示例:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
题解:
首先,对于一个容器的大小,取决于两侧柱子较矮的那根的高度,以及两侧柱子之间的距离。
初始left = 0,right = height.length-1
当height[left]<=height[right]
时,对于以left
为柱的所有容器的高度h
,必有h≤height[left]
,而此时right
距离left
最远,因此当前是以left
为柱的容量最大的情况,用这个容量尝试更新答案后,left
这跟柱子就不需要再考虑,因此left++
。height[right]<height[left]
时同理。
复杂度O(n),代码如下:
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length-1;
int ans = Integer.MIN_VALUE;
while(left<right){
if(height[left]<height[right]){
int square = height[left] * (right-left);
ans = ans > square ? ans : square;
left++;
}else{
int square = height[right] * (right-left);
ans = ans > square ? ans : square;
right--;
}
}
return ans;
}
}