mediumTwo PointersPattern: Two Pointers
Max Contained Volume Solution
Problem Statement
Given a list of non-negative integers `heights` representing the heights of containers, find the maximum volume of liquid that can be stored between any two containers, where the volume is calculated as the minimum height of the two containers multiplied by the distance between them.
Examples
Example 1:
Input:[1,8,6,2,5,4,8,3,7]
Output:49
Explanation: The maximum volume that can be stored is between silos of height 7 and 8, with a distance of 8 - 1 = 7 and a minimum height of 7, giving a volume of 7 * 7 = 49.
Example 2:
Input:[1,1]
Output:1
Explanation: The maximum volume that can be stored is between silos of height 1 and 1, with a distance of 1 and a minimum height of 1, giving a volume of 1 * 1 = 1.
Constraints
- 2 <= n <= 10^5
- 0 <= heights[i] <= 10^4
Time: O(N) Space: O(1)
Two pointers at start and end. Calculate area (min height * width). Move the pointer pointing to the shorter line inward, as moving the taller line can never increase the area. Time O(N), Space O(1).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
