LeetCode: Container With Most Water
问题描述
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i,height).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example1
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example2
Input: height = [1,1]
Output: 1
方法思路
首先想到的方法是嵌套循环遍历数组,复杂度为O(n2), 但是程序运行结果超出了限制,因此复杂度应该控制在O(n), 即遍历一次数组。因为有两个因素会影响容器的容积,即宽度(两点之间的距离),最小高度(两个点对应的值中较小的一个), 初始宽度设置最大((height.length - 1) - 0)并逐渐缩小宽度,再乘以最小高度并将结果与当前最大容积进行比较以决定是否更新最大容积,在完成比较后,比较两个点对应的值,在宽度缩小的情况下,要使容积变大,就只能抛弃更小的高度值以此来进行循环。
代码如下(示例):
class Solution {
public int maxArea(int[] height) {
int l = 0;
int r = height.length-1;
int maxArea = 0;
while(l<r){
maxArea = Math.max( maxArea, Math.min(height[l],height[r])*(r-l) );
if(height[l] < height[r]){
l++;
}else{
r--;
}
}
return maxArea;
}
}