11. Container With Most Water
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Two Pointers
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven an array of bar heights, find two bars that together with the x-axis form a rectangle holding the maximum amount of water, returning that maximum area.
Approach
- Place two pointers at the leftmost and rightmost bars; the area is
(right - left) * min(height[left], height[right]). - Always advance the pointer sitting at the shorter bar inward, because the current bar is the bottleneck — any move from the taller side can only keep or shrink width while the height is still capped by the shorter bar, so it can never beat the current answer.
- Moving the shorter bar inward is the only way to discover a potentially taller bar that might compensate for the reduced width.
- This greedy scan guarantees we never miss the optimal pair while visiting each element at most once.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0, right = static_cast<int>(height.size()) - 1;
int best = 0;
while (left < right) {
// Area is limited by the shorter of the two bars
int water = (right - left) * min(height[left], height[right]);
best = max(best, water);
// Advance the pointer at the shorter bar — keeping the taller one
// is the only chance to improve the height constraint
if (height[left] < height[right])
++left;
else
--right;
}
return best;
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int maxArea(vector<int>& height) {
int numOfLines=height.size();
int left=0;
int right=numOfLines-1;
int maxWater=0;
while(right>left){
maxWater=max(maxWater, (right-left)*min(height[left], height[right]));
if(height[right]<height[left])
right--;
else
left++;
}
return maxWater;
}
};
// Time: O(N)
// Space: O(1) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.