LeetCode Top 100 Liked Questions 11. Container With Most Water (Java版; Medium)
题目描述
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.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
classSolution{publicintmaxArea(int[] height){int n = height.length;int left =0, right = n -1;int max =0;while(left<right){
max = Math.max(max, Math.min(height[left], height[right])*(right-left));if(height[left]<height[right]){
left++;}else{
right--;}}return max;}}
为什么短边可以舍弃? 因为保留短边的话, 另一个指针再怎么移动也只能减少面积
I know that some people are still having a hard time understanding this proof, but please re-read original proof a few times.
Here is my example hope it helps.
[4 (left) , 9, 12, 7 , 8, 14 (right) ] --------> this array is indexed from 1 to 6 and we looks at left and right and compare the value
So eliminate all pairs of index [1,2], [1,3],[1,4],[1,5] <- here the index[] means possible windows of solutions (4,9), (4,9,12), (4,9,12,7)...
Why? area of window [1,6] = (6 - 1) * MIN(4, 14) = 20
all the windows that have [1,2...5] even if all the numbers on the right are changed to infinity must be less than 20.
EX:
(5-1) * min(4, infinity) < 20 for all right indicies less than 6.
So this means its ok to exclude all windows starting with index 1
If you apply this at each step over and over again you can get an O(n) algorithm.
Hope this helps.