11. Container With Most Water
Intuition
Complexity
Space Complexity
Time Complexity
Code
public int maxArea(int[] heights) {
int maxWater = 0; // To store the maximum area found
int left = 0; // Left pointer starting at the beginning
int right = heights.length - 1; // Right pointer starting at the end
while (left < right) {
// Height of the container is limited by the shorter line
int currentHeight = Math.min(heights[left], heights[right]);
// Width of the container is the distance between the two pointers
int width = right - left;
// Calculate the current area and update max if it's larger
int currentArea = currentHeight * width;
maxWater = Math.max(maxWater, currentArea);
// Move the pointer pointing to the shorter line inward
if (heights[left] < heights[right]) {
left++;
} else {
right--;
}
}
return maxWater; // Return the maximum area found
}
Last updated