Description Link to heading
Solution Link to heading
The violent solution of this problem has a time complexity of $O(n^2)$, to reduce the time complexity, we consider two-pointers.
So, we need determine how left pointer l and right pointer r will meet each other:
if (height[l] >= height[r]), the capacity depends onheight[r]. Ifl++, the capacity will become smaller, so we shouldr--.if (height[l] < height[r]), the capacity depends onheight[l]. Ifr--, the capacity will become smaller, so we shouldl++.
Code Link to heading
#include <vector>
using std::vector;
class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size() - 1;
int res = 0;
while (l < r) {
if (height[l] >= height[r]) {
res = max(res, (r - l) * height[r]);
r--; // l++ will make capacity smaller
} else {
res = max(res, (r - l) * height[l]);
l++; // r-- will make capacity smaller
}
}
return res;
}
};