SprintCode.pro

Подготовка к алгоритмическим задачам

Super

Container With Most Water

You are given an integer array heights where heights[i] represents the height of the ith bar.

You may choose any two bars to form a container. Return the maximum amount of water a container can store.

Example 1:

Input: heights = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: In this case, the maximum area of water (49) will be between bars with heights 8 and 7

Example 2:

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

Recommended time and space complexity

The optimal solution should have O(n) time complexity and O(1) space complexity, where n is the length of the array.


Hint 1

The area of the container is determined by two factors: width (distance between bars) and height (minimum height of the two chosen bars).


Hint 2

Instead of checking all possible pairs of bars (which gives O(n²)), think about using two pointers starting from opposite ends of the array.


Hint 3

At each step, you should move the pointer pointing to the smaller height, as this is the only way to potentially increase the container area.

This problem tests the ability to efficiently find the maximum area of a water container using the two-pointer algorithm. It helps develop optimization skills and working with arrays, as well as improves understanding of spatial geometry and algorithmic complexity.

Expected Input :

[1,8,6,2,5,4,8,3,7]

Expected Output

49