标签:
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.
Subscribe to see which companies asked this question
思路:
参考:https://leetcode.com/discuss/1074/anyone-who-has-a-o-n-algorithm
先看代码,然后看证明。
证明:
反证法:假如我们得到的结果不是最优的,那必定有一个比我们更好的结果,他的左右横坐标分别为a_l和a_r。
因为我们的循环直到两根指针相遇才结束,也就是说我们必定在某个时刻有一个指针指向了a_l或者a_r但是没有同时指向他们。不失一般性的,假设在这个时刻,我们指向了a_l,但没指向a_r,此时a_l有以下两种情况会发生变化:
所有情况都矛盾,得证。
java code:
public class Solution { public int maxArea(int[] height) { int maxArea = 0; int lo = 0; int hi = height.length-1; while(lo < hi) { maxArea = Math.max(maxArea, (hi-lo) * Math.min(height[lo], height[hi])); if(height[lo] < height[hi]) lo++; else hi--; } return maxArea; } }
LeetCode:Container With Most Water
标签:
原文地址:http://blog.csdn.net/itismelzp/article/details/51615173