Python coding

Most water between two walls

heights[i] is the height of a vertical wall standing at position i on flat ground. Pick two walls: the water between them rises only as high as the shorter one, so they hold min(heights[i], heights[j]) * (j - i) units. Walls in between do not get in the way. Return the most water any pair can hold, or 0 with fewer than two walls.

Aim for one pass with O(1) extra space.

Besides the tests, one large input (3,000 walls) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • max_water([1,8,6,2,5,4,8,3,7]) → 49
  • max_water([1,1]) → 1
  • max_water([4,3,2,1,4]) → 16
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Start with the widest pair: lo = 0, hi = len(heights) - 1. Each step, move one end inward and keep the best area.

Hint 2

Move the shorter wall. Any closer partner gives it less width while its own height still caps the water, so it can never do better.

Solution and why it works
pythonO(n) · O(1)
def max_water(heights: list[int]) -> int:
    lo, hi = 0, len(heights) - 1
    best = 0
    while lo < hi:
        best = max(best, min(heights[lo], heights[hi]) * (hi - lo))
        if heights[lo] < heights[hi]:
            lo += 1
        else:
            hi -= 1
    return best

The shorter wall caps the water. Paired with any wall closer in, it gets less width and no more height, so it can never beat the current area: drop it and move that end inward. Each step discards one wall for good, so the scan is O(n) instead of checking O(n²) pairs. Moving the taller wall instead can skip the best pair.

Related lab: Loops in motion