Open songyy5517 opened 6 months ago
Approach: Two Pointers & Greedy
left
and right
pointing at the left and the right side of the array at the beginning;max_area
: a global variable to record the maximum area.max_area
.Complexity Analysis
class Solution {
public int maxArea(int[] height) {
// Intuition: Two Pointers (Collision Pointers) & Array travarsal.
// 1. Exception handling
if (height == null || height.length < 2)
return 0;
// 2. Define two collision pointers
int left = 0, right = height.length - 1;
int max_area = 0;
// 3. Loop through the array
while (left < right) {
// Calculate the area
int h = Math.min(height[left], height[right]);
max_area = Math.max(max_area, (right - left) * h);
// Update the smaller pointer (Greedy)
if (height[left] < height[right])
left ++;
else
right --;
}
return max_area;
}
}
2024/5/11
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 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:
Intuition This problem is to find two lines with the most water in the container. From the description, for two lines
h[i]
andh[j]
, we can infer thatarea_water = min(h[i], h[j]) * |i - j|
. Therefore, we can use two (collision) pointers left and right first pointing at the left and the right side of the array respectively. In this way,|i - j|
can be the maximum. Next, what we need to do is to move the two pointers towards each other when scanning the entire array, and find the pair that minimizes the water area. Throughout the scan,|i - j|
would be descending. Therefore, to find the maximum value ofarea_water
, we should exclude the cases where bothmin(h[i], h[j])
and|i - j|
decreases. So for each step, we have two linesheight[left]
andheight[right]
, we move the smaller one to the next position and calculate the area.