Suppose we have a list of numbers representing heights of bars in a histogram. We have to find area of the largest rectangle that can be formed under the bars.
So, if the input is like nums = [3, 2, 5, 7]
then the output will be 10
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, heights): stk = [-1] heights.append(0) ans = 0 for i in range(len(heights)): while heights[i] < heights[stk[-1]]: h = heights[stk.pop()] w = i - stk[-1] - 1 ans = max(ans, h * w) stk.append(i) return ans ob = Solution() nums = [3, 2, 5, 7] print(ob.solve(nums))
[3, 2, 5, 7]