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
2
3
4
5
6
7
8
// Not efficient: O(n^2)
int max = 0;
for (int i = 0; i < height.length; i++) {
for (int j = i + 1; j < height.length; j++) {
int area = (j - i) * Math.min(height[i], height[j]);
max = Math.max(max, area);
}
}
  • ❌ 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 and right
  • 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int maxArea = 0;

while (left < right) {
int h = Math.min(height[left], height[right]);
int width = right - left;
int area = h * width;
maxArea = Math.max(maxArea, area);

// Move the shorter line inward
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}

return maxArea;
}
}

⏱ 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.