算法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.

image

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

给n个非负整数,每个代表一个坐标(i, ai)。把这些点画到一个二维坐标图里,然后把(i, ai)与(i, 0)相连形成线。找到两个线,使得之间能装最多的水。

提示:不能倾斜,n最少为2。
思路一,我们可以暴力的两层遍历,每一个条线与另外一条线能装多少水,记录最多的一个。时间复杂度为O(n2),空间复杂度为O(1)。
思路二,比较投巧,因为默认两条线的距离一样。我们从头和尾开始遍历,计算两条线能装多少水,然后比较头、尾大小,头小头++,否则尾--(为了防止出现头尾一样大的情况)。记录最大的空间。时间复杂度为O(n),空间复杂度为O(1)。

以下为代码:

public int maxArea(int[] height) {
    int max = 0, l = 0, r = height.length - 1;
    
    while (l < r) {
        max = Math.max(max, Math.min(height[l], height[r]) * (r - l));
        if(height[l] < height[r]) {
            l++;
        } else {
            r--;
        }
    }
    
    return max;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,424评论 0 10
  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 2,198评论 0 3
  • 写在前面: 程序员分两种,会算法的程序员和不会算法的程序员。几乎没有一个一线互联网公司招聘任何类别的技术人员是不考...
    蓝色小石头阅读 746评论 0 2
  • 网络初级13期 坚持分享67天 赞美到细节,及时鼓励、奖励,被强化会越来越好。协助孩子在他做到时,或相对做到时及时...
    希言_HY阅读 94评论 0 0
  • 明日之后高分子涂层获得方法有四种,第一种是在沙石堡、夏尔镇、白树高地开启特殊宝箱获得,第二种是击败各野外地图的不明...
    画球球阅读 285评论 0 0