← All Exercises

Container With Most Water

basicjavascript~25min

Background

The two-pointer shrinking argument is a classic example of eliminating candidates without checking every pair.

Problem

Given an array of non-negative heights, choose two lines that together with the x-axis form the largest container, and return its area.

Input

An array of at least two non-negative integers representing line heights at consecutive x positions.

Output

An integer equal to the maximum area min(height[i], height[j]) * (j - i).

Sample tests

Sample 1

Input: heights = [1,8,6,2,5,4,8,3,7]
Expected: 49

Sample 2

Input: heights = [1,1]
Expected: 1

Sample 3

Input: heights = [4,3,2,1,4]
Expected: 16

Your solution

Learning objective

Prove a two-pointer elimination rule and implement a linear scan instead of checking all O(n^2) pairs.