算法思路:
Explanation:
-
Two-pointer technique:
- Start with two pointers, one at the beginning (
left
) and one at the end (right
) of theheight
array. - Calculate the area formed between the two vertical lines. The area is calculated as: Area = ( right − left ) × min ( height[left] , height[right] ) \text{Area} = (\text{right} - \text{left}) \times \min(\text{height[left]}, \text{height[right]}) Area=(right−left)×min(height[left],height[right])
- Move the pointer that points to the shorter line inward (either
left
orright
), as moving the shorter line has the potential to increase the maximum area. - Repeat this process until the two pointers meet.
- Start with two pointers, one at the beginning (
-
Time Complexity:
- The solution runs in
O
(
n
)
O(n)
O(n), where
n
n
n is the number of elements in the
height
array, because each element is processed at most once.
- The solution runs in
O
(
n
)
O(n)
O(n), where
n
n
n is the number of elements in the
代码:
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size() - 1;
int maxWater = 0;
while(left < right) {
int currentWater = (right - left) * min(height[left], height[right]);
if(height[left] >= height[right]) {
right--;
}else {
left++;
}
maxWater = max(maxWater, currentWater);
}
return maxWater;
}
};