Algo-Sim › Two Pointers
Container With Most Water
Medium · Two Pointers · step through it in Java, Python and C++ on your own input
Pick two walls that, with the x-axis, hold the most water. Always move the shorter wall inward.
Problem
You are given n vertical walls, where wall i stands at x = i with height height[i]. Choose two walls; together with the x-axis they form a container that holds min(height[i], height[j]) · (j − i) units of water. Return the largest amount any pair can hold.
Constraints
- 2 ≤ height.length ≤ 10⁵
- 0 ≤ height[i] ≤ 10⁴
- n up to 10⁵ rules out trying every pair
Edge cases to test
- Two walls only
- All walls the same height
- The tallest walls sit at the ends
Follow-up questions
- Why is moving the shorter wall always safe?
- Any container using the shorter wall and a wall further in is narrower and no taller, so the shorter wall can be discarded: O(n) total.
- How does this differ from Trapping Rain Water?
- Here you choose two walls and ignore the ones in between; there every bar traps water up to the lower of its tallest walls on each side.
Solution
Java
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int best = 0;
while (left < right) {
int h = Math.min(height[left], height[right]);
best = Math.max(best, h * (right - left));
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}Python
def max_area(height):
left, right = 0, len(height) - 1
best = 0
while left < right:
h = min(height[left], height[right])
best = max(best, h * (right - left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxArea(vector<int> &height) {
int left = 0, right = int(height.size()) - 1;
int best = 0;
while (left < right) {
int h = std::min(height[left], height[right]);
best = std::max(best, h * (right - left));
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)