Leetcode 11. Container With Most Water
You are given an array height
of n
non-negative integers where each element represents the height of a vertical line on a 2D plane. The goal is to find two lines such that, together with the x-axis, they form a container that holds the maximum amount of water.
Return the maximum amount of water a container can store.
Given the array height = [1,8,6,2,5,4,8,3,7]
, the maximum amount of water the container can store is 49
(formed by the lines at index 1
and 8
).
To solve this problem efficiently, we can use the two-pointer approach:
left = 0
) and one at the end (right = n-1
) of the array.This approach ensures an efficient O(n) time complexity with a single pass through the array.
#include <vector>
#include <algorithm>
class Solution {
public:
int maxArea(std::vector<int>& height) {
int left = 0;
int right = height.size() - 1;
int max_area = 0;
while (left < right) {
int current_area = (right - left) * std::min(height[left], height[right]);
max_area = std::max(max_area, current_area);
if (height[left] < height[right]) {
++left;
} else {
--right;
}
}
return max_area;
}
};
The time complexity of this solution is O(n), where n
is the number of elements in the input array. This is because we only make a single pass through the array with the two pointers, moving them towards the center.
The space complexity is O(1), as we are only using a fixed amount of extra space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?