We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Data Structures
- Stacks
- Largest Rectangle
- Discussions
Largest Rectangle
Largest Rectangle
Sort by
recency
|
617 Discussions
|
Please Login in order to post a comment
This is one of the hard ones. I watched a YouTube video on how to solve it. And here is my code. It is pretty descriptive IMHO. Easy to read. The key is whenever the height decreases, the previous taller builds effectively reached the end of their lives. And we can calculate their max areas. And we can extend the starting position of the new lower height to the leftest one that is 'killed' by this new lower height. Adding a '0' to the end of the height so that at the end, all the leftover heights are killed by this '0' and we can calculate their max areas.
def largestRectangle(h):
Here's my Java 8 solution, passing all test cases, for Max Score of 50.
While solving this problem, I could think of three approaches: two using Explicit Stacks, while one using Implicit Stack (via Recursion). All three of them pass ALL Test-Cases, for a Max Score of 50. All of them have been provided in the code, with some explanatory comments.
def largestRectangle3(h):
Brute force solution without stacks that passes some tests but only fails with time limit exceeded. So, I'd say logic is correct. This is O(N!) algorithm, it generates all the possible arrangements of size 1, size 2, .... size N. Absolutely not optimal but it uncovers the neccessary thought pattern to solve optimally.
def largestRectangle(h): maxRectangleArea = float("-inf")
took me 4 hours to do this, the logic is to find how much range that the number [i] can spread. spread is spread to max [index left] and to max [index right] starting from [i]. the valid range is when the number is higher than [i] number. i dont know if this acceptable since i dont use stack at all.