题目:
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.
解答:
struct Position {
int height;
int i;
};
class Solution {
public:
int maxArea(vector<int>& height) {
if (height.size() <= 1) {
return 0;
}
vector<Position> startPositions;
int curMaxNum = height[0];
Position pos;
pos.height = curMaxNum;
pos.i = 0;
startPositions.push_back(pos);
for (int i = 0; i != height.size(); ++i) {
if (curMaxNum < height[i]) {
curMaxNum = height[i];
Position pos;
pos.height = curMaxNum;
pos.i = i;
startPositions.push_back(pos);
}
}
vector<Position> endPositions;
curMaxNum = height[height.size() - 1];
pos.height = curMaxNum;
pos.i = height.size() - 1;
endPositions.push_back(pos);
for (int i = height.size() - 1; i >= 0; --i) {
if (curMaxNum < height[i]) {
curMaxNum = height[i];
Position pos;
pos.height = curMaxNum;
pos.i = i;
endPositions.push_back(pos);
}
}
int maxArea = 0;
for (int i = 0; i != startPositions.size(); ++i) {
for (int j = 0; j != endPositions.size(); ++j) {
Position start = startPositions[i];
Position end = endPositions[j];
int curArea = (start.height < end.height ? start.height : end.height) * (end.i - start.i);
if (curArea > maxArea) {
maxArea = curArea;
}
}
}
return maxArea;
}
};