Data Structures & Algorithms Two Pointers
💡
Exercise 38

Container With Most Water 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given n non-negative integers representing heights of vertical lines, find two lines that together with the x-axis form a container that holds the most water.

height = [1,8,6,2,5,4,8,3,7] # Output: 49 # Lines at index 1 (h=8) and index 8 (h=7) # Area = min(8,7) * (8-1) = 7 * 7 = 49

Greedy two-pointer approach: start with widest container (left=0, right=end). Move the shorter line inward — because moving the taller line can only decrease or maintain area.

Time: O(n), Space: O(1) — much better than O(n²) brute force!

📋 Instructions
Implement `max_area(height)` using two pointers. Test with `height = [1,8,6,2,5,4,8,3,7]` and print the result.
Left at 0, right at end. Calculate area = min(height[left], height[right]) * (right - left). Track max area. Move the pointer with the shorter height inward.
🧪 Test Cases
Input
max_area([1,8,6,2,5,4,8,3,7])
Expected
49
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.