11. Container With Most Water 🏞️
Difficulty: Medium - Tags: Array, Two Pointers, Greedy
Problem Statement 📜
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith 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.
Examples 🌟
🔹 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.
Constraints ⚙️
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
Solution 💡
To solve this problem, we can use the Two-Pointer Technique:
Initialize Two Pointers: Start with
leftpointer at the beginning (0) andrightpointer at the end (n - 1) of the array.Calculate Area: For each pair of lines, calculate the area formed by the lines at
leftandright, which is given bymin(height[left], height[right]) * (right - left).Move the Pointer:
Move the pointer pointing to the shorter line inward (either increment
leftor decrementright).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.
Java Solution
Time Complexity ⏳
O(n), where
nis the length of the array. We scan the array once using two pointers.
Space Complexity 💾
O(1), since we only use a constant amount of extra space.
You can find the full solution here.
Last updated
Was this helpful?