Back

Container With Most Water

medium

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i-th line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.

Test Cases

Copy an input into the main harness and Run to verify
Input
height = [1,8,6,2,5,4,8,3,7]
Expected Output
49

Explanation: The lines at index 1 and index 8 have heights 8 and 7, separated by 7 units: min(8,7) * 7 = 49.

Input
height = [1,1]
Expected Output
1

Constraints

  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4

Hints

Hint 1 — click to reveal

Area is width times the *shorter* of the two lines — the taller line is never the limit.

Hint 2 — click to reveal

Start with the widest possible container and ask which side you can afford to give up.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.