Container With Most Water – Solution & Complexity
1. Understand the Area Formula
- Choose two vertical lines at indices
leftandright. - The width is
right - left. - The height of the water is limited by the shorter line.
- Area is
(right - left) * min(height[left], height[right]).
2. Brute Force Idea
- Check every pair of lines and compute its area.
- Keep the maximum area found.
- This is simple but O(n²), which is too slow for large arrays.
3. Use Two Pointers
- Start with the widest possible container: first and last lines.
- Compute the area, then move one pointer inward.
- Moving the taller line cannot help because the shorter line still limits the height while width shrinks.
- Therefore, always move the pointer at the shorter line.
4. Update the Best Area While Moving
- At each step, calculate the current area.
- Update
bestif this area is larger. - Move
leftwhen the left line is shorter, otherwise moveright.
5. Final Solution and Complexity
- The two pointers scan inward in one pass.
- Every possible useful candidate is considered without checking all pairs.
- Time complexity is O(n).
- Space complexity is O(1).