码迷,mamicode.com
首页 > 其他好文 > 详细

11. Container With Most Water

时间:2016-11-30 11:26:51      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:bottom   integer   init   rgb   ant   ace   repr   round   bit   

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;
    }
};







11. Container With Most Water

标签:bottom   integer   init   rgb   ant   ace   repr   round   bit   

原文地址:http://www.cnblogs.com/zhxshseu/p/e7ebd6efa97c7d01f62016cd3f748d85.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!