Problem:
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.
分析:
题目即为求(i, ai),(i, 0),(j, aj),(j, 0)组成的图形的最大矩形面积面积(以ai和aj中小者为矩形的高)。
利用二分法,冲首位两边缩进,每次求得面积与最大面积比较并更新,
同时对ai,aj中小者的位置进行更新(大者可能会成为下一次的高以更新面积;而小者不变只能得到小于等于小者的高,且宽度在减小无法更新面积)。
AC Code(C++):
class Solution {
public:
//45 / 45 test cases passed.
//Runtime: 29 ms
int maxArea(vector<int>& height) {
//排除无效情况
if (height.size() < 2) {
return 0;
}
int begin = 0;
int end = (int)height.size() - 1;
int container = 0;
while (begin < end) {
int size = min(height[begin], height[end])*(end - begin);
if (size > container) {
container = size;
}
if (height[begin] < height[end]) {
++begin;
}
else{
--end;
}
}
return container;
}
};