C++ 0011.cpp
class Solution {
public:
int maxArea(vector<int>& height) {
map<int, int> last;
for (int i = 0; i < height.size(); i++)
last[height[i]] = i;
auto maxx = 0;
vector<int> prune;
for (int i = 0; i < height.size(); i++)
{
int left = height.size() - i;
int minHeight = maxx / left;
prune.clear();
auto l = last.lower_bound(minHeight);
for (; l != last.end(); l++)
{
auto h = l->first;
auto w = l->second - i;
if (w <= 0)
{
prune.push_back(h);
continue;
}
auto area = min(h, height[i]) * w;
if (maxx < area)
maxx = area;
}
// prune
for (auto h : prune)
last.erase(h);
}
return maxx;
}
};
Difficulty
and has an acceptance rate of about 61% (9+ million submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic “container with most water” problem. It iterates over each possible left boundary, keeps track of the farthest right index for every height value, and computes candidate areas only when they can improve the current best result. By discarding heights that can no longer contribute to a larger area, the algorithm reduces unnecessary work.
Building the Height-to-Index Map
The first phase creates a map that records, for each distinct height, the last (rightmost) index where that height appears. This map enables constant-time lookup of the farthest right position for any height value.
map<int, int> last;
for (int i = 0; i < height.size(); i++)
last[height[i]] = i;
Because the map stores the most recent index for each height, later lookups always refer to the furthest possible right boundary for that height.
Outer Iteration Over Left Boundaries
The algorithm walks the array from left to right, treating each position i as the left wall of a potential container. For each i it computes the maximum possible width remaining (left) and derives a lower bound on the height (minHeight) that could beat the current maximum area (maxx). This bound allows the inner search to skip heights that are guaranteed to be too small.
auto maxx = 0;
vector<int> prune;
for (int i = 0; i < height.size(); i++)
{
int left = height.size() - i;
int minHeight = maxx / left;
// ...
}
Selecting Candidate Right Walls
Inside the outer loop, the code uses last.lower_bound(minHeight) to start iterating from the smallest height that meets the derived lower bound. For each candidate height h, it computes the width w as the distance from the current left index i to the stored rightmost index for h. If the width is non-positive, the height cannot serve as a right wall for this left position and is marked for removal.
prune.clear();
auto l = last.lower_bound(minHeight);
for (; l != last.end(); l++)
{
auto h = l->first;
auto w = l->second - i;
if (w <= 0)
{
prune.push_back(h);
continue;
}
auto area = min(h, height[i]) * w;
if (maxx < area)
maxx = area;
}
The min(h, height[i]) expression ensures the container height is limited by the shorter of the two walls, matching the problem definition.
Pruning Unusable Heights
After processing all candidates for a given left index, the algorithm removes any heights that produced a non-positive width. Since those heights are located at indices left of or equal to the current i, they can never serve as a right wall for any later left index, and eliminating them shrinks the map for subsequent iterations.
for (auto h : prune)
last.erase(h);
Edge Cases Handled
When the computed width w is zero or negative, the code treats the height as irrelevant for the current left position and schedules it for removal. This situation occurs when the rightmost occurrence of a height lies at or before the current left index, meaning no container can be formed with that height as the right wall. By pruning such entries, the algorithm gracefully handles arrays where heights repeat or where the maximum area is formed early in the scan.
The lower-bound calculation (minHeight = maxx / left) also implicitly handles the case where the current best area is zero. In that scenario minHeight becomes zero, causing the inner loop to consider all heights, which is necessary for the first successful area computation.
Performance Optimizations
The use of a map to store the last occurrence of each height provides ordered access, enabling the lower_bound operation to jump directly to the smallest height that could improve the result. This avoids scanning heights that are too short to matter.
Pruning heights whose rightmost index is no longer to the right of the current left pointer reduces the size of the map over time. As the outer loop progresses, the map becomes progressively smaller, leading to fewer iterations in the inner loop and faster lookups.
The calculation of minHeight based on the current maximum area and remaining width creates a dynamic threshold. By raising this threshold as maxx grows, the algorithm discards increasingly larger groups of heights that cannot beat the best area found so far, focusing computational effort on promising candidates only.
ELI5 - Simplified Explanation
Imagine a row of tall wooden fences standing in a garden, and each fence has a different height. This program wants to find the biggest rectangular swimming pool that can be built between any two of those fences.
To build a pool, you pick two fences to act as the walls. The water inside the pool needs to stay as high as the shorter of the two walls, because if the water goes any higher, it would spill over the shorter side. The width of the pool is just the distance between those two fences on the ground. To find the secret of the biggest pool, the code keeps track of where the last fence of every height is located.
The code goes on a trip across the fence row, starting from the very first one all the way to the end. For every fence it visits, it tries to see if it can build a bigger pool by pairing the current fence with other fences that exist further down the line. It uses a clever trick to ignore fences that are too short to possibly make a bigger pool than the one already found. If it finds a combination that holds more water, it remembers that new, larger size. It also cleans up its list by getting rid of fences that can no longer help make a bigger pool, which keeps everything moving quickly. By the time it finishes looking at all the fences, it knows exactly how big the largest possible pool can be.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||||
| WalkCCC | C++ | Python | Java | |||||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | JS | C | Go | PHP | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||
| Progiez | C++ | Python | Java | |||||||||||
| github | aylei | Rust | ||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| Dijkstra-Edu | Java | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| trung-hn | Python | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| withaarzoo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| zfang399 | C++ | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| Dijkstra-Edu | Java | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| trung-hn | Python | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| withaarzoo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 42: Trapping Rain Water
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality