Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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】

暴力拆解,找出所有的组合,返回其中最大的。但是这样运行会超时,代码如下:

 public class Solution {
public int maxArea(int[] height) {
if(height == null || height.length == 0) return 0;
int max = 0;
for(int i = 0; i < height.length - 1; i++){
for(int j = i + 1; j < height.length; j++){
int minH = Math.min(height[i], height[j]);
max = Math.max(max, (j - i)*minH);
}
}
return max;
}
}

【思路2】

The brute force solution can definitely lead us to the right answer just by doing too many redundant comparisons. When two pointer approach comes to mind, it is intuitive to set both pointers i, j at each end of this array, and move them strategically to the middle of array, update the answer during this process return the answer when we reach the end of array. Suppose now we have the scenarios below:

7, 5, 6, 9

i        j

When i = 1, j = 4,

ans = min(7, 9) * (4 - 1) = 21

What's next? Should we move i or j? We notice that to calculate the area, the height is really identified by the smaller number / shorter end between the two ends, since it's required that you may not slant the water, so it sounds like Bucket theory: how much water a bucket can contain depends on the shortest plank. So, as to find the next potential maximum area, we disregard the shorter end by moving it to the next position. So in the above case, the next status is to move i to the left,

7, 5, 6, 9

   i     j

update:

area (i, j) = area(2, 4) = min(5, 9) * (4 - 2) = 10
ans = max(21, 10) = 21

You may notice that, if we move j instead, you actually get a larger area for length of 2:

area (i, j) = area(1, 3) = min(7, 6) * (3 - 1) = 18

Does that mean this approach will not work? If you look at this way, we move pointer as to get the next potential max, so it doesn't need to be the maximum for all combinations with length l. Even though 18 is greater than 10, it's smaller than 21 right? So don't worry, we can move on to find the next potential maximum result. Now we need to prove, why disregard the shorter end can safely lead us to the right answer by doing a little maths.

Given an array: a1, a2, a3, a4, ai, ......, aj, ......, an
i j

Assume the maximum area so far is ans, we prove that

"By moving shorter end pointer further doesn't eliminate the final answer (with two ends at maxi, maxj respectively) in our process"

Suppose we have two ends at (i, j) respectively at this moment:

(i) If the final answer equals what we have already achieved, it's done! In this scenario, we must have

maxi <= i, maxj >= j

(ii) Otherwise, we know as we move any pointer further, the length of the next rectangle decreases, so the height needs to increase as to result in a larger area. So we have

min(height[maxi], height[maxj]) > min(height[i], height[j])

So the smaller one in height[i], height[j] won't become any end in the maximum rectangle, so it's safe to move forward without it.

Till now, it has been proved that this approach can work in O(n) time since we advance one end towards the middle in each iteration, and update ans takes constant time in each iteration.

代码如下:

 public class Solution {
public int maxArea(int[] height) {
int ans = 0;
int i = 0, j = height.length - 1;
while(i < j){
ans = Math.max(ans, (j - i) * Math.min(height[i], height[j]));
if(height[i] > height[j]) j--;
else i++;
} return ans;
}
}

LeetCode OJ 11. Container With Most Water的更多相关文章

  1. 《LeetBook》leetcode题解(11):Container With Most Water[M] ——用两个指针在数组内移动

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  2. 【LeetCode】11. Container With Most Water 盛最多水的容器

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:盛水,容器,题解,leetcode, 力扣,python ...

  3. 【LeetCode】11. Container With Most Water

    题目: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...

  4. leetcode problem 11 Container With Most Water

    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). ...

  5. Leetcode Array 11 Container With Most Water

    题目: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...

  6. leetcode 11. Container With Most Water 、42. Trapping Rain Water 、238. Product of Array Except Self 、407. Trapping Rain Water II

    11. Container With Most Water https://www.cnblogs.com/grandyang/p/4455109.html 用双指针向中间滑动,较小的高度就作为当前情 ...

  7. Leetcode 11. Container With Most Water(逼近法)

    11. Container With Most Water Medium Given n non-negative integers a1, a2, ..., an , where each repr ...

  8. LeetCode Array Medium 11. Container With Most Water

    Description Given n non-negative integers a1, a2, ..., an , where each represents a point at coordin ...

  9. leetcode面试准备:Container With Most Water

    leetcode面试准备:Container With Most Water 1 题目 Given n non-negative integers a1, a2, ..., an, where eac ...

随机推荐

  1. Java中集合框架体系

    集合的体系结构:     |--Collection(单列集合的根接口)         |--List(子接口):元素是有序的,元素可以重复.因为该集合体系有索引.             |--A ...

  2. c++中string类型可以直接进行比较

    以下代码在Ubuntu14.10下实现 /*------------------------- filename is demo.cpp --------------------------*/ #i ...

  3. 启动Mysql报错:Another MySQL daemon already running with the same unix socket.

    启动Mysql报错: Another MySQL daemon already running with the same unix socket. 删除如下文件即可解决 /var/lib/mysql ...

  4. IntentService和Service的区别

    整个看下来是一个Service+Thread+handle的结合体, Service:比Activity的被kill的级别低 Thread:不阻塞UI线程 Handle:队列式的消息循环 那这个玩意的 ...

  5. 搭建git代码服务器

    在代码管理中,通常需要使用版本管理工具,git就是一个不错的选择,这里简单罗列一下git服务器的搭建过程. 1. 安装git工具包 2. 初始化git库:在代码服务器上,通常只需要创建一个不含有工作目 ...

  6. 关于 div随网页居中问题

    可以先在外部设置个 宽高 小于浏览器的 div 内容再根据 最外层 定位 这个代码是 左右居中的 <div style=" width:300px; height:300px; mar ...

  7. 在.Net MVC中自定义ValidationAttribute标签对Model中的属性做验证

    写一个继承与ValidationAttribute类的自定义的验证方法 MVC中传递数据时,大多数都会用Model承载数据,并且在传到控制器后,对Model进行一系列的验证. 我平时经常使用的判断方法 ...

  8. Linux服务器性能指标查询命令安装

    Linux命令扫盲 之 sar   今天在读<大规模Web服务开发技术>一书的时候,书中提到了sar这个命令,感觉很有用,有必要整理学习一下.(对于一位Linux初学者,不能放过任何一个学 ...

  9. EFI安装Win7

    安装系统之前电脑里最好没有其他系统,安装过程中电脑需重启多次,其他系统会引导电脑开机,无法完成WIN7安装. 一.制作安装分区 1.首先在移动硬盘(U盘)准备一个FAT32分区 一定要FAT32分区, ...

  10. JAVA多态问题总结(课堂总结)

    面向对象的三大特性:封装.继承.多态.从一定角度来看,封装和继承几乎都是为多态而准备的.这是我们最后一个概念,也是最重要的知识点.多态的定义:指允许不同类的对象对同一消息做出响应.即同一消息可以根据发 ...