Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Container With Most Water

Arrays & Two-Pointersmedium

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Given an array `heights` where `heights[i]` is the height of a vertical line at index `i`, find two lines that together with the x-axis form a container that holds the most water. Return the maximum water volume. Volume = min(heights[i], heights[j]) × (j − i).

Sample tests

Input: maxWater([1,8,6,2,5,4,8,3,7])
Output: 49
Input: maxWater([1,1])
Output: 1

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Brute force checks every pair in O(n^2).
  • Moving the taller side never increases the area, so always move the shorter one.

Learning resources

  • MDN: Math.min
Approach & explanation (try first)

Two pointers from both ends, always advancing the shorter wall, find the max area in O(n) time, O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.