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.
You don't really need any stack to tackle this problem. Just one array holding the heights would be enought. Then you can work out the maximum rectangle as you go through the building heights. My python3 solution with the comments is below:
n=int(input())h=[int(x)forxininput().split(" ")]# For each element(height) of an array,# 1. Search the continuous buildings to the left# - if continous building is at the same height or taller, increment the count# 2. Seach the continuous buildings to the right# - if continous building is at the same height or taller, increment the count# 3. Calculate the current rectangle area: # - height of the current building * current count# 4. Check if the current area is larger than the current maximum area# When the search finishes print the maximum area acquired.max_area=0foriinrange(len(h)):cnt=0forjinrange(i,-1,-1):ifh[j]>=h[i]:cnt+=1else:breakforkinrange(i+1,len(h)):ifh[k]>=h[i]:cnt+=1else:breakarea=h[i]*cntifarea>max_area:max_area=areaprint(max_area)
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 →
You don't really need any stack to tackle this problem. Just one array holding the heights would be enought. Then you can work out the maximum rectangle as you go through the building heights. My python3 solution with the comments is below: