Container With Most Water
Medium arrays · two-pointers
Description
Constraints
2 <= n <= 100000; 0 <= height
Examples
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Hints (1)
- Start with the widest pair and always move the shorter line inward.
Solutions
Two pointers, move the shorter side in. · Time O(n) · Space O(1)
func maxArea(height []int) int {
i, j, best := 0, len(height)-1, 0
for i < j {
h := height[i]
if height[j] < h {
h = height[j]
}
if area := h * (j - i); area > best {
best = area
}
if height[i] < height[j] {
i++
} else {
j--
}
}
return best
}
Two pointers, move the shorter side in. · Time O(n) · Space O(1)
function maxArea(height) {
let i = 0, j = height.length - 1, best = 0;
while (i < j) {
best = Math.max(best, Math.min(height[i], height[j]) * (j - i));
if (height[i] < height[j]) i++; else j--;
}
return best;
}
Two pointers, move the shorter side in. · Time O(n) · Space O(1)
function maxArea($height) {
$i = 0; $j = count($height) - 1; $best = 0;
while ($i < $j) {
$area = min($height[$i], $height[$j]) * ($j - $i);
if ($area > $best) { $best = $area; }
if ($height[$i] < $height[$j]) { $i++; } else { $j--; }
}
return $best;
}
Two pointers, move the shorter side in. · Time O(n) · Space O(1)
def maxArea(height):
i, j, best = 0, len(height) - 1, 0
while i < j:
best = max(best, min(height[i], height[j]) * (j - i))
if height[i] < height[j]:
i += 1
else:
j -= 1
return best
Two pointers, move the shorter side in. · Time O(n) · Space O(1)
function maxArea(height: number[]): number {
let i = 0, j = height.length - 1, best = 0;
while (i < j) {
best = Math.max(best, Math.min(height[i], height[j]) * (j - i));
if (height[i] < height[j]) i++; else j--;
}
return best;
}
Create a free account to submit solutions, track progress and save problems.
Create account