Algorithm-Day05-Container-With-Most-Water-lc#11
🧩 Problem Description
You are given an integer array height
of length n
. There are n
vertical lines drawn such that the two endpoints of the i-th line are (i, 0)
and (i, height[i])
.
Find two lines that, together with the x-axis, form a container that holds the most water.
Return the maximum amount of water a container can store.
Example:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
💡 Naive Approach (Brute Force)
Try every pair (i, j)
and calculate the area between them.
1 | // Not efficient: O(n^2) |
- ❌ Too slow for large inputs
- ✅ Correct, but time complexity is O(n²)
💡 Optimal Approach (Two Pointers)
Use two pointers from both ends and move the shorter line inward:
- At each step, compute area between
left
andright
- Move the pointer with the shorter height
- Keep track of the max area seen so far
This gives us O(n) time.
🔢 Java Code
1 |
|
⏱ Time and Space Complexity
- Time Complexity: O(n)
One pass using two pointers. - Space Complexity: O(1)
No extra space used.
✍️ Summary
- Two-pointer technique works because width shrinks as we move, so we must maximize height wisely.
- Brute-force fails time constraint; optimal method relies on greedy shrinking of shorter side.
- One of the most elegant sliding-window-style problems.
This pattern is key for problems involving “max area”, “longest distance with constraint”, etc.