【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 and n is at least 2.
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.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
思考:使用两个指针left跟right,从数组头跟数组尾分别向中间逼近。
储水量是由当前left跟right的距离与较低端的乘积
当height[left] > height[right]时,right--。因为要保留最高高度,才有可能获取到更大的储水量max
同理,当height[right] > height[left]时,left++;
具体代码如下:
class Solution {
public int maxArea(int[] height) {
if(height.length <= 1) {
return 0;
}
int left = 0;
int right = height.length - 1;
int max = 0;
while(left < right) {
max = Math.max(max,Math.min(height[left],height[right]) * (right - left));
if(height[right] > height[left]){
left++;
} else {
right--;
}
}
return max;
}
}