Container With Most Water
Algorithm/TwoPointers
Intuition
The task is to find the maximum amount of water that can be held between two lines from the given array height
. This problem can be efficiently solved using the two-pointer approach.
By starting with two pointers at the ends of the array, we try to maximize the area by moving the pointers towards each other based on the heights of the lines.
Approach
Below is the step-by-step breakdown of the approach:
- Initialize Two Pointers:
left
pointer starts at the beginning of the array.right
pointer starts at the end of the array.
- Calculate Area:
- In each iteration, compute the area between the lines at
left
andright
. - Use
Math.min(height[left], height[right])
to determine the height of the container since the water level is constrained by the shorter line.
- In each iteration, compute the area between the lines at
- Update Maximum Area:
- Compare the current area with the previously stored maximum (
ans
) and update if the current area is larger.
- Compare the current area with the previously stored maximum (
- Move the Pointers:
- Move the pointer pointing to the shorter line since a taller line might create a larger area when paired with future lines.
- Return the Maximum Area:
- When the two pointers meet, we have checked all possible containers, and
ans
will hold the largest area.
- When the two pointers meet, we have checked all possible containers, and
Complexity
- Time Complexity: , where
n
is the length of theheight
array. Each element is visited at most once. - Space Complexity: , as only a constant amount of extra space is used.