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
|
612 Discussions
|
Please Login in order to post a comment
def largestRectangle(h):
why my approach is incorrect?
def largestRectangle(h): i=0 largestArea = 0 height = math.inf while h: if h[-1]>height: h.pop(-1) else: height= h.pop(-1) i+=1 area = height*i if area>largestArea: largestArea = area return largestArea
find the previous smaller element and the next smaller element in O(n) time
total time requires 2 pass over the vector. so O(n) for total time.
Thank you very much for your code! Two comments here: 1) your time of execution will depend on the input, If for each h, both next smaller and previous smaller elements are not far, it may be O(n). But in the opposite extreme case, e.g. when H is sorted, it will be O(n^2) 2) Still why stacks? Why not find next smaller and previous smaller for each element naively? (see e.g. solution by faisalalotibi98). It would be the same running time
it does appear to be O(n^2) on 1st glance, that's wat i thought too when i first saw it. the naive way really takes O(n^2), the stack is there to guarantee O(n)
but every number in H is pushed onto the stack exactly once, and is removed at most once, so the inner while loop add up to a maximum of 2n operations for all iterations of i
i learned this algo from copilot, u should ask it, it'll explain to u in detail why its O(n) and not O(n^2). just type "c++ explain the previous smaller element algorithm and why its O(n)"
My code is working, but can anyone please explain to me in a simple way what this problem has to do with stacks?
ur method uses recursion and is definitely at least O(n^2), i cant be bothered to figure out the exact time of this recursion, but note that the brute force method is O(n^2).
furthermore, there are issues with ur possible_ans, ur creating a local storage in each call stack, not a global storage and passing it by reference during recursion.
the question wants O(n)
if u had no time out its because the test cases are weak
look at my method, its O(n)