Container With the Most Water

Try to solve the Container With the Most Water problem.

Statement#

You’re given an integer array height of length nn, and there are nn vertical lines drawn such that the two endpoints of the ithi^{th} line are (i,0)(i, 0) and (ii, height[i]).

Find two lines from the input array that, together with the x-axis, form a container that holds as much water as possible. Return the maximum amount of water a container can store.

Note: You may not slant the container.

Constraints:

  • n=n = height.length

  • 22 \leq nn 103\leq 10^3

  • 00 \leq height[i] 103\leq 10^3

Examples#

Created with Fabric.js 3.6.6 height 2 8 6 3 5 4 7 Output 35 Input Output Explanation Sample example 1 There are five blocks of water between the columnwith the heights 7 and 8. We select the minimum ofthe two heights, which is 7 and multiply that by 5 to get 35.

1 of 2

Created with Fabric.js 3.6.6 Input Output Explanation height 8 2 6 3 5 4 7 Output 42 Sample example 2 There are six blocks of water between the columnwith the heights 7 and 8. We select the minimum ofthe two heights, which is 7 and multiply that by 6 toget 42.

2 of 2

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Container With the Most Water

1

What is the maximum amount of water a container can store if we have the following input?

height = [1, 1]

A)

1

B)

2

C)

0

Question 1 of 20 attempted

Try it yourself#

Implement your solution in the following coding playground.

An optimal solution to this problem runs in O(n) time and takes O(1) space.

Python
usercode > main.py
Input #1
%0 node_01 1 node_11 8 node_21 6 node_31 2 node_41 5 node_51 4 node_61 8 node_71 3 node_81 7
Visualization for Input #1
Container With the Most Water

You might want to go over the Two Pointers pattern again.

Solution: Valid Palindrome

Solution: Container With the Most Water