11. Container With Most Water #2246
-
Topics: You are given an integer array Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum amount of water that can be contained between two vertical lines in an array, where the amount of water is determined by the distance between the lines and the height of the shorter line. The solution involves using the two-pointer technique to efficiently find the maximum area without checking all possible pairs, which would be inefficient. Approach
Let's implement this solution in PHP: 11. Container With Most Water <?php
/**
* @param Integer[] $height
* @return Integer
*/
function maxArea($height) {
$maxArea = 0;
$left = 0;
$right = count($height) - 1;
while ($left < $right) {
$currentArea = ($right - $left) * min($height[$left], $height[$right]);
$maxArea = max($maxArea, $currentArea);
if ($height[$left] < $height[$right]) {
$left++;
} else {
$right--;
}
}
return $maxArea;
}
// Test cases
// Example 1
echo maxArea([1,8,6,2,5,4,8,3,7]) . "\n"; // Output: 49
// Example 2
echo maxArea([1,1]) . "\n"; // Output: 1
?> Explanation:
This approach efficiently narrows down the possible pairs of lines to check, ensuring optimal performance with a time complexity of O(n), where n is the number of elements in the array. The space complexity is O(1) as we only use a few variables regardless of the input size. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum amount of water that can be contained between two vertical lines in an array, where the amount of water is determined by the distance between the lines and the height of the shorter line. The solution involves using the two-pointer technique to efficiently find the maximum area without checking all possible pairs, which would be inefficient.
Approach