11. Container With Most Water
Container With Most Water - LeetCode
Container with Most Water - GeeksforGeeks
Approach :
- This implies that if there was a better solution possible, it will definitely have the Height greater than min(a1, aN).
- We know that, Base min(a1, aN)
This means that we can discard min(a1, aN) from our set and look to solve this problem again from the start. - If a1 < aN, then the problem reduces to solving the same thing for a2, aN.
- Else, it reduces to solving the same thing for a1, aN-1
In the two-pointer solution for the "Container With Most Water" problem, the key idea is to maximize the area formed by the vertical lines at the left
and right
pointers. The area between two lines is determined by both the height of the shorter line and the distance between the two pointers. The decision to "move the pointer at the shorter line inward" helps us optimize this process.
Why move the pointer at the shorter line inward?
-
The area between two lines is calculated as:
Area=min(height[left],height[right])×(right−left)\text{Area} = \min(\text{height}[left], \text{height}[right]) \times (\text{right} - \text{left})The width between the two pointers decreases as the pointers move toward each other. So, to maximize the area, the height must increase to compensate for the loss in width.
-
The height of the container is determined by the shorter of the two lines (because the water can't be taller than the shorter side). If you move the pointer at the shorter line inward, you might find a taller line, which could increase the height and potentially lead to a larger area.
Key Logic:
- If
height[left] < height[right]
, this means the line atleft
is the shorter one. To find a potentially taller line and increase the area, move the left pointer inward (left++
). - If
height[left] >= height[right]
, the line atright
is the shorter or equal. To increase the height, you move the right pointer inward (right--
).
By always moving the pointer at the shorter line, you give yourself the chance to find a taller line and potentially maximize the area.