Advertisement
Sunilsai

Maximum_Rectangle_Size_Histogram

May 29th, 2022
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. def largestRectangleArea(heights):
  2.     leftSmall = []
  3.     rightSmall = [-1]*len(heights)
  4.     stack = []
  5.     for i in range(len(heights)):
  6.         while(stack and heights[i] <= stack[-1][1]):
  7.             stack.pop()
  8.         if(stack):
  9.             leftSmall.append(stack[-1][0]+1)
  10.         else:
  11.             leftSmall.append(0)
  12.         stack.append([i,heights[i]])
  13.     stack = []
  14.     for i in range(len(heights)-1, -1, -1):
  15.         while(stack and heights[i] <= stack[-1][1]):
  16.             stack.pop()
  17.         if(stack):
  18.             rightSmall[i] = stack[-1][0]-1
  19.         else:
  20.             rightSmall[i] = len(heights)-1
  21.         stack.append([i, heights[i]])
  22.     res = 0
  23.     for i in range(len(heights)):
  24.         val = (rightSmall[i]-leftSmall[i]+1)*heights[i]
  25.         res = max(res, val)
  26.     return res
  27.  
  28. heights = [2, 1, 5, 6, 2, 3, 1]
  29. print(largestRectangleArea(heights))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement