1. Problem Statement (Simple Explanation):
You’re given an array height of length n.
At each index i, there is a vertical line from (i, 0) to (i, height[i]).
Choose two different lines, at indices i and j (i < j), and form a container with the x-axis.
The amount of water this container can hold is:
area=(j-i)×min(height[i],height[j])
You must find the maximum possible area over all pairs (i, j) and return it.
You cannot tilt/slant the container.
2. Examples:
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Possible pairs (showing a few):
Lines at 1 and 8 (0-based indices):
width = 8 − 1 = 7, min height = 8 → area = 56 (not actually correct; max is 49 using lines 1 and 8 indices 1 & 8? Let’s pick correct example)
The optimal pair is at indices 1 and 8 (heights 8 and 7):
width = 8 - 1 = 7
height = min(8, 7) = 7
area = 7 * 7 = 49
Output: 49
Example 2:
Input: height = [1,1]
Only one pair: indices 0 and 1:
width = 1
height = min(1, 1) = 1
area = 1 * 1 = 1
Output: 1
3. Approach 1 – Brute Force (O(n²)):
Intuition:
Try all pairs of lines (i, j):
Compute area for each pair.
Track the maximum.
Algorithm:
Initialize maxArea = 0.
For each i from 0 to n - 1:
For each j from i + 1 to n - 1:
width = j - i
height = min(height[i], height[j])
area = width * height
Update maxArea = max(maxArea, area).
Return maxArea.
Pseudo-code (Brute Force):
Time: O(n²) → too slow for n up to 10^5.
Space: O(1) extra.
We need a better solution.
4. Approach 2 – Two Pointers (Optimal, O(n)):
This is the classic solution.
Intuition:
We want:
max0≤i<j<n(j-i)⋅min(height[i],height[j])
Key observation:
The area is limited by the shorter of the two lines.
For a fixed pair (i, j), if we want a bigger area, we need:
a larger width or
a taller minimum height.
We start with the widest container:
left = 0, right = n - 1.
Then:
Compute area for (left, right).
Move one pointer inward:
Always move the pointer that points to the shorter line.
Why?
Because:If we move the pointer at the taller line, the width decreases, and the min height stays limited by the shorter line (which we kept), so the area cannot increase by moving the taller one.
Only by moving the shorter one can we possibly find a taller line that may increase min(height[left], height[right]) enough to compensate for the smaller width.
We repeat until left >= right.
Algorithm (Step-by-Step):
Initialize:
left = 0
right = n - 1
maxArea = 0
While left < right:
width = right - left
h = min(height[left], height[right])
area = width * h
Update maxArea = max(maxArea, area)
If height[left] < height[right]:
move left++ (trying to find a taller left line)
Else:
move right-- (trying to find a taller right line)
After loop, return maxArea.
Pseudo-code (Two Pointers):
Complexity:
Time: O(n)
Space: O(1)
Meets constraints and is the standard optimal solution.
5. Java code:
6. C code:
7. C++ code:







Comments
Post a Comment