1 题目要求:
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 and n is at least 2.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
2 解决方法:
枚举法,挨个计算水量更新最大值。由大到小比情况较为复杂,由小至大比较时,仅当新的边长比旧的边长大才有可能获得更大水量,作为条件简化。
class Solution {
public:
int maxArea(vector<int>& height) {
int maxwater = 0, i = 0, j = height.size() - 1;
while (i < j) {
int h = min(height[i], height[j]);
maxwater = max(maxwater, (j - i)*h);
while (height[i] <= h && i < j)i++;
while (height[j] <= h && i < j)j--;
}
return maxwater;
}
};
时间复杂度O(n)
空间复杂度O(1)