Hone logo
Hone
Problems

Container With Most Water

Given an array of non-negative integers representing the heights of vertical lines, find two lines that together with x-axis forms a container capable of containing the most water. This problem tests your ability to efficiently search through data and optimize for a specific outcome, a common task in various fields like resource management and optimization algorithms.

Problem Description

You are given an array heights where heights[i] represents the height of the i-th vertical line. Each line has a width of 1. You need to find two lines such that when they are connected by a horizontal line, they form a container. The container's area is determined by the shorter line's height and the distance between the two lines. Your task is to calculate the maximum possible area that such a container can hold.

What needs to be achieved:

  • Iterate through all possible pairs of lines in the heights array.
  • For each pair, calculate the area of the container formed.
  • Keep track of the maximum area found so far.
  • Return the maximum area.

Key Requirements:

  • The area of a container is calculated as (right_index - left_index) * min(heights[left_index], heights[right_index]).
  • The right_index must always be greater than the left_index.

Expected Behavior:

The function should return an integer representing the maximum area of a container that can be formed.

Edge Cases to Consider:

  • Empty input array: Return 0.
  • Array with only one element: Return 0.
  • Array with all zeros: Return 0.
  • Arrays with varying heights and distances.

Examples

Example 1:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The container formed by the lines at indices 1 and 8 (heights[1] = 8 and heights[8] = 7) holds the most water, with an area of (8 - 1) * min(8, 7) = 7 * 7 = 49.

Example 2:

Input: [1,1]
Output: 1
Explanation: The container formed by the lines at indices 0 and 1 (heights[0] = 1 and heights[1] = 1) holds the most water, with an area of (1 - 0) * min(1, 1) = 1 * 1 = 1.

Example 3:

Input: [4,3,2,1,4]
Output: 16
Explanation: The container formed by the lines at indices 0 and 4 (heights[0] = 4 and heights[4] = 4) holds the most water, with an area of (4 - 0) * min(4, 4) = 4 * 4 = 16.

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4
  • The time complexity should be O(n). A brute-force O(n^2) solution will likely time out for larger inputs.

Notes

Consider using a two-pointer approach to efficiently find the maximum area. The key idea is to start with the widest possible container (outermost lines) and move the pointer associated with the shorter line inward. This is because moving the taller line inward will always result in a smaller or equal area. Think about how the area changes as you move the pointers.

Loading editor...
plaintext