Statement
Solution
Naive approach
A naive approach to solve this problem would be to find the area of every possible pair of vertical lines and select the maximum area out of them.
The time complexity for this approach would be , where is the length of the input array. The space complexity would be , since only a constant amount of extra space is used.
Optimized approach using two pointers
An optimized approach to solve this problem is using two pointers, start
and end
, initialized at the beginning and end of the array, respectively. We also create a variable to store the maximum area and set it to zero.
While iterating through the array, height
, the algorithm proceeds through the following steps:
- Calculate the distance,
width
, between the two vertical lines pointed bystart
andend
pointer aswidth
end
start
. - The height of the container is determined by the shorter of the two vertical lines pointed by the
start
andend
pointers. Then, multiply this height by thewidth
to calculate the area of the container. - If the calculated area is greater than the current value of the maximum area, update the maximum area.
- Move the pointer pointing to the shorter vertical line inward by one step. This is because if we try to move the pointer at the longer vertical line, we won’t gain any increase in area, since the shorter line limits it.
- Keep iterating through the array until the pointers meet.
After iterating through the array, return the maximum area.
Now, let’s look at the following illustration to get a better understanding of the solution: