11. Container With Most Water ๐๏ธ
Last updated
Last updated
Difficulty: Medium
- Tags: Array
, Two Pointers
, Greedy
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 1:
Input:
Output:
Explanation: The maximum area is formed between lines at index 1 and index 8, with height 8 and 7, respectively. This gives an area of min(8,7) * (8 - 1) = 7 * 7 = 49
.
๐น Example 2:
Input:
Output:
Explanation: The only container possible is formed by the two lines, giving an area of min(1,1) * (1 - 0) = 1
.
n == height.length
2 <= n <= 10^5
0 <= height[i] <= 10^4
To solve this problem, we can use the Two-Pointer Technique:
Initialize Two Pointers: Start with left
pointer at the beginning (0) and right
pointer at the end (n - 1) of the array.
Calculate Area: For each pair of lines, calculate the area formed by the lines at left
and right
, which is given by min(height[left], height[right]) * (right - left)
.
Move the Pointer:
Move the pointer pointing to the shorter line inward (either increment left
or decrement right
).
By moving the shorter line, we maximize the chance of finding a taller line to potentially increase the container area.
Track the Maximum Area: Keep updating the maximum area found during each iteration.
Repeat until the two pointers meet.
O(n), where n
is the length of the array. We scan the array once using two pointers.
O(1), since we only use a constant amount of extra space.
You can find the full solution here.