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.
题意:假设有一个x,y的二维坐标,我们定义area(i,j) = min(xi,xj) * |i - j, 找出最大的area。
思路:用两个指针l,r分别指向数组两边,然后计算当前area,接着比较xl,xr大小,小的那个的下标变化。知道l>=r|。 这是由于当前的矩形宽度是最大的,那么接下来的矩形想想面积比当前的面积大,就只能够增加矩形的高。算法复杂度为O(N)
代码:
public int maxArea(int[] height) {//O(N) int max = 0; int curr = 0; int l = 0, r = height.length - 1; while (l < r){ curr = Math.min(height[l],height[r]) * (r - l); max = Math.max(max, curr); if(height[l] < height[r]){ l ++; }else if(height[l] > height[r]){ r --; }else { l ++; r --; } } return max; }
[LeetCode]Container With Most Water
原文:http://blog.csdn.net/youmengjiuzhuiba/article/details/45176327