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.
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):
h.append(0)
alive = [[0, h[0]]]
maxArea = 0
for pos, val in enumerate(h):
if pos == 0:
continue
if len(alive)>0 and val < alive[-1][1]:
while len(alive)>0 and val < alive[-1][1]:
dead = alive.pop()
maxArea = max(maxArea, dead[1]*(pos-dead[0]))
start = dead[0]
alive.append([start, val])
else:
alive.append([pos, val])
return maxArea
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Largest Rectangle
You are viewing a single comment's thread. Return to all comments →
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):