DSA Factory
Free Arrays lessonsArrays · Stage 10 · Mastery · Step 3

Widest container

Pick two walls that hold the most water. About 12 minutes.

What can you rule out?

Checking every pair of walls takes about n × n steps. Every fast idea in this topic worked by ruling things out instead: the two fingers dropped a number for good, the window dropped the left end.

So ask: which walls could never be part of a better container than the best you've found? Start with the widest possible pair, the two ends, and think about which one can go.

Start wide: the two ends are the widest pair.
Wall heights [1, 8, 6, 2, 5, 4, 8, 3, 7]
1
0
8
1
6
2
2
3
5
4
4
5
8
6
3
7
7
8
leftright
best
8
water
8

The widest pair first: the water rises only as high as the shorter wall (1), across a width of 8, so it holds 8. The 1 can't do better with any closer partner, so drop it.

Move 1 of 6
Quick check

The two end walls are 3 tall (left) and 8 tall (right). Which one can you safely drop?

  1. AThe 3 on the left
  2. BThe 8 on the right
  3. CBoth
Show the answer

The 3 on the left. Any other partner for the 3 is closer, and the water can never rise above 3.

Your problem

Widest container

You get the heights of walls standing in a row, one per position. Two walls and the ground between them form a container holding min(height i, height j) × (j − i) water. Return the most water any two walls can hold.

Example
heights = [1, 8, 6, 2, 5, 4, 8, 3, 7] → 49

2 ≤ n ≤ 1,000,000 · 0 ≤ each height ≤ 10^6 · return a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve