Leetcode 11: Container With Most Water

grid47
grid47
Exploring patterns and algorithms
Nov 5, 2024 5 min read

A serene water container being filled with calming light, symbolizing capacity and volume.
Solution to LeetCode 11: Container With Most Water Problem

You are given an array of integers where each integer represents the height of a vertical line drawn on a 2D plane. The x-axis is represented by the index of the array, and each line’s height corresponds to the value at that index. Your task is to find two lines that, along with the x-axis, form a container that can hold the most water. The container’s area is determined by the distance between the lines and the height of the shorter line.
Problem
Approach
Steps
Complexity
Input: You are given an integer array 'height' of length 'n'.
Example: height = [2, 5, 7, 3, 9, 4]
Constraints:
• 2 <= n <= 10^5
• 0 <= height[i] <= 10^4
Output: Return the maximum area of water that the container formed by two lines can hold.
Example: Output: 30
Constraints:
• The maximum area must be a non-negative integer.
Goal: To maximize the water area, we need to find the optimal pair of lines and calculate the area between them.
Steps:
• Start by initializing two pointers: one at the beginning and one at the end of the array.
• Calculate the area between the lines at the current pointers.
• Move the pointer pointing to the shorter line towards the other pointer to potentially find a larger area.
• Repeat the process until the two pointers meet.
Goal: Ensure that the solution handles large inputs efficiently.
Steps:
• The array must have at least 2 elements.
• The array length can go up to 100,000.
Assumptions:
• The input array contains only non-negative integers representing heights.
Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Explanation: In this case, the maximum area is formed by the lines at index 1 and index 8. The area is calculated as min(8, 7) * (8 - 1) = 49.

Input: height = [3, 9, 1, 8, 6, 4]
Explanation: The maximum area is formed by the lines at index 1 and index 3. The area is calculated as min(9, 8) * (3 - 1) = 16.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus