题目链接: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 and n is at least 2.
(1)思路:两个指针分别从容器的左右向中间移动直到相遇,检查移动的过程中形成容量最大的容器。
(2)代码:
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size(), ans = -1, i = 0, j = n-1;
while (i < j) {
if (height[i] < height[j]) {
ans = ans > height[i]*(j-i) ? ans : height[i]*(j-i);
i++;
}
else {
ans = ans > height[j]*(j-i) ? ans : height[j]*(j-i);
j--;
}
}
return ans;
}
};
(3)提交结果:
·