Skills101
← All coding problems

Container With Most Water

mediumTwo Pointers+20 XPTime limit 2s

There are n vertical lines; line i stands at position i with height h[i]. Choose two lines that, together with the x-axis, hold the most water. The water held by lines i < j is (j − i) × min(h[i], h[j]).

Input:

  • line 1: n
  • line 2: n heights

Output: the maximum amount of water.

Constraints: 2 ≤ n ≤ 10⁵, 0 ≤ h[i] ≤ 10⁴.

Think about it: start with the widest container (both ends). Moving the taller line inward can never help — so always move the shorter one.

Sample input 1

9
1 8 6 2 5 4 8 3 7

Sample output 1

49

Sample input 2

2
1 1

Sample output 2

1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.