Intermediate Level

Implement the containerWithMostWaterArea method that returns the maximum water area formed by two vertical lines.

The input contains an array height and its length size. Each value represents the height of a vertical line at that index.

Your task is to choose two lines that can form a container with the x-axis and return the maximum amount of water the container can hold.

The water area is calculated as the distance between the two lines multiplied by the shorter line height. For example, the best pair in [1,8,6,2,5,4,8,3,7] gives area 49.

Example 1

Input
height (int[]) = [1,8,6,2,5,4,8,3,7]
size (int) = 9
Returns (int) 49

Example 2

Input
height (int[]) = [1,1]
size (int) = 2
Returns (int) 1

Example 3

Input
height (int[]) = [4,3,2,1,4]
size (int) = 5
Returns (int) 16

Use the two-pointer technique.

Start with one pointer at the beginning and one at the end because this gives the widest container. Calculate the area, then move the pointer that has the smaller height.

Moving the taller side cannot improve the area because the shorter side still limits the water height. Continue until both pointers meet.

Pseudocode:

function containerWithMostWaterArea(height, size):
    left = 0
    right = size - 1
    best = 0
    while left < right:
        width = right - left
        waterHeight = minimum(height[left], height[right])
        area = width * waterHeight
        best = maximum(best, area)
        if height[left] < height[right]:
            left++
        else:
            right--
    return best
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.