approach 1
two pointer approach
When we see the problem, we would use two heightest bars to form the max area. But some pair of shorter bars may form a larger area since they are wider. That means we should check every wider area.
Let’s see in another view. Say we have two bars to form an area. The next step is to check if some bars inside could form a larger area. Noticing that the bottom is shorter, which means this larger area must have two higher bars. So our goal is to find two higher bars between two border bars.
C++ code
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
int i = 0, j = height.size() - 1; // two borders.
while (i < j){ // shorten the width to find two highter bars.
res = max(res, (j - i) * min(height[i], height[j]));
if (height[i] < height[j]) i++; else j--; // fix the higher side, we will eventually get there.
}
return res;
}
};