11. Container With Most Water
#two-pointers
Problem
Intuition
Time Complexity
Space Complexity
Solution
class Solution {
public int maxArea(int[] height) {
// n -> heights.length, number of heights
// Time Complexity: O(n), we need to process all the heights
// Space Complexity: O(1), no extra space except few variables are used
// It can also be called as auxillary space complexity
int start = 0;
int end = height.length - 1;
int maxArea = Integer.MIN_VALUE;
// Loop until the start and end pointers meet
while (start < end) {
int startHt = height[start]; // Height at the start pointer
int endHt = height[end]; // Height at the end pointer
int width = end - start; // Width of the container
int area = 0; // Area of the container
// Calculate the area based on the shorter height
if (startHt <= endHt) {
area = startHt * width;
start++; // Move the start pointer towards the center
} else {
area = endHt * width;
end--; // Move the end pointer towards the center
}
// Update the maximum area if necessary
maxArea = Math.max(maxArea, area);
}
return maxArea;
}
}
Last updated
Was this helpful?