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







posted @ 2016-11-30 11:00  copperface  阅读(183)  评论(0编辑  收藏  举报