You're given an array arr
, which represents the heights of stairs in a staircase. You want to hide a rectangular treasure chest below the stairs. Return the area of the largest treasure chest that you can hide.
Example 1:
Example 2:
You can solve this problem with a brute-force method by guessing each possible rectangular boundary which takes O(n2) time, but you should always try to do better than brute-force. Dynamic Programming is just as bad, so we need to use another method.
To use a single-pass method, the idea is to extend rectangles as we walk along the array. For example, the very 1st rectangle gets extended like this:
The full algorithm is to extend all possible rectangles. We'll keep track of all the indexes we're extending in an array called extending
:
We want to stop extending the rectanges at some point. The idea is to stop extending all the rectangles that are taller than the current rectangle, because we can't fit them under the stairs anymore, so they're as big as they possibly can be.
This is almost the full solution, but right now if we just extend as we walk rightwards, we miss some solutions. Consider the orange rectangle below, for example. It turns out we can include the solutions we're missing, by just pretending any new rectangles have been extended from an earlier point. We can pretend new rectangles have been extended starting from the the leftmost rectangle that just stopped (the 5 in the example).
Once you start coding this idea, notice that the entries in extending
will always be sorted by increasing height, because we stop extending rectangles when they decrease in height. This means we can stop extending the correct rectangles simply by popping the array repeatedly, until we've removed all entries taller than the current height. This happens to be a stack.
Here's the full code:
Time Complexity O(n). We loop through every element in the array. Every elements enters and exists the extending
array once.
Space Complexity O(n). The extending array grows to a size of O(n).