CodePark/ problems / Container With Most Water
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Two pointers

Container With Most Water

mediumabout 20 minutes in an interview

heights is an array of non-negative whole numbers. Think of each one as a wall: at position i stands a wall heights[i] tall.

Pick any two walls i < j and fill the space between them with water. The water can't rise above the shorter wall, so the amount held is (j - i) * Math.min(heights[i], heights[j]). That is the gap between the walls times the shorter height. Walls in between don't get in the way.

Return the largest amount any pair can hold.

  • With fewer than two walls, return 0.
  • heights has up to 100,000 elements.
Input: heights = [2, 5, 4, 8, 3, 6] Output: 20Walls at position 1 (height 5) and position 5 (height 6): distance 4 × height 5.
Input: heights = [3, 3] Output: 3
Input: heights = [7] Output: 0