LeetCode No.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.

 

容量最多容器,形容的还挺形象。

最初的想法是找到两个最高的,逐步向外扩展,但最后表明会遗漏一些情况。于是我卡主了,移步Discuss,看到了一个极简单的贪心算法,当然,当时并未理解。贴下代码如下:

class Solution {
public:
    int maxArea(vector<int> &height) {
        int i = 0, j = height.size() - 1;
        int mArea = 0;

        while (i < j) {
            mArea = max(mArea, (j - i) * min(height[i], height[j]));
            if (height[i] < height[j]) i++;
            else j--;
        }

        return mArea;
    }
};

关键就是如何移动i和j。可以看出,i和j总是向着较高的一个移动,这就保证了总能移动到最多的情况。

posted @ 2015-01-27 13:32  _Anonyme  阅读(108)  评论(0编辑  收藏  举报