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
Return:
(int) 49
Example 2
Input:
height (int[]) = [1,1]
size (int) = 2
Return:
(int) 1
Example 3
Input:
height (int[]) = [4,3,2,1,4]
size (int) = 5
Return:
(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
Run your code to see the result.