Container With Most Water
Container With Most Water
You are given n non-negative integers representing heights of vertical lines at positions 1 through n. Find two lines that together with the x-axis form a container that holds the most water. The amount of water a container holds = min(height[left], height[right]) × (right - left). Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=9, heights=[1 8 6 2 5 4 8 3 7] → 49
Input format — only if your code reads from stdin
Input format (stdin): - First line: integer n (number of heights) - Second line: n space-separated non-negative integers Output: a single integer — the maximum water the container can hold.
Approach
Two-pointer greedy: start with left=0 and right=n-1. Compute current area = min(h[left], h[right]) × (right-left), update max. Move the pointer with the smaller height inward — this is the only way to potentially increase area.
Input
Output
- •
2 ≤ n ≤ 10^5, 0 ≤ height[i] ≤ 10^4
More Arrays problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards