LeetCode No.11 Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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总是向着较高的一个移动,这就保证了总能移动到最多的情况。