11. Container With Most Water

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.

解析

找出两个线段,从而和x轴围成的面积最大
画一个矩阵, 列代表右侧线段, 行代表左侧线段
如下图, x 代表我们不需要考虑该情况的面积

首先我们计算处于位置 (1,6) 的面积,以 o 表示。如果现在左侧线段 小于 右侧, 意味着所有在(1,6) 左侧的面积都比当前的小。所以我们就不需要计算这些元素了 (以 --- 替代)。所以该情况,left++
1
2
3
4
5
6
7
   1 2 3 4 5 6
1 x ------- o
2 x x
3 x x x
4 x x x x
5 x x x x x
6 x x x x x x

我们接下来到位置 (2,6)。此时,如果右侧的线段更短,说明所有在 (2,6) 以下的元素都不用计算了。所以 right--
1
2
3
4
5
6
7
   1 2 3 4 5 6
1 x ------- o
2 x x       o
3 x x x     |
4 x x x x   |
5 x x x x x |
6 x x x x x x

无论最后 o 是什么样的路径, 我们只需要找到该路径上的最大值即可, 路劲只包含 n-1 个cases。
1
2
3
4
5
6
7
   1 2 3 4 5 6
1 x ------- o
2 x x - o o o
3 x x x o | |
4 x x x x | |
5 x x x x x |
6 x x x x x x

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class  Solution {
public :
     int  maxArea(vector< int >& height) {
         int  len = height.size(), left = 0, right = len -1;
         int  maxarea = 0;
         while (left < right){
             maxarea = max((right - left) * min(height[left], height[right]), maxarea);
             if (height[left] < height[right])
                 left ++;
             else
                 right --;
         }
         return  maxarea;
     }
};







转载于:https://www.cnblogs.com/zhxshseu/p/e7ebd6efa97c7d01f62016cd3f748d85.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值