leetcode 151: Container With Most Water

来源:互联网 发布:protty网络验证 编辑:程序博客网 时间:2024/06/07 06:49

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 linei 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.


1. brute force ( O(n^2)) 超时.

2. i,j 间 不共享重复的SUBCASE. 不适合使用Dynamic Programming.

3. greedy 方法适用.

                //因为i是短板,所以如果无论j往前移动到什么位置,都不可能产生比area更大的面积                //换句话所,i能形成的最大面积已经找到了,所以可以将i向前移。 [1]


public class Solution {    public int maxArea(int[] height) {        int sz = height.length;        int max = 0;                int l=0, r=sz-1;                while(l<r) {            int area = (r-l) * Math.min(height[l], height[r]);            max = max>area? max:area;            if(height[l]<height[r]) {                ++l;            } else {                --r;            }        }        return max;    }}


Reference:

[1] http://blog.unieagle.net/2012/09/16/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Acontainer-with-most-water/


0 0
原创粉丝点击