- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find largest rectangle area under histogram in python

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 −

- stk := a stack and initially insert -1 into it
- insert 0 at the end of heights
- ans := 0
- for i in range 0 to size of heights, do
- while heights[i] < heights[top of stk], do
- h := heights[top of stk] and pop from stk
- w := i - top of stk - 1
- ans := maximum of ans and (h * w)

- push i into stk

- while heights[i] < heights[top of stk], do
- return ans

Let us see the following implementation to get better understanding −

## Example

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))

## Input

[3, 2, 5, 7]

## Output

10

- Related Questions & Answers
- Largest Rectangle in Histogram in Python
- C++ Program to Find Largest Rectangular Area in a Histogram
- Python Program to Find the Area of a Rectangle Using Classes
- Java program to find the area of a rectangle
- Program to find area of largest island in a matrix in Python
- Program to find area of largest submatrix by column rearrangements in Python
- Golang Program to Find the Area of a Rectangle Using Classes
- Area of largest triangle that can be inscribed within a rectangle in C Program?
- Area of Largest rectangle that can be inscribed in an Ellipse?
- Largest Triangle Area in Python
- Rectangle Area in C++
- Program to find area of largest square of 1s in a given matrix in python
- Area of the largest triangle that can be inscribed within a rectangle?
- Rectangle Area II in C++
- C Program for Area And Perimeter Of Rectangle

Advertisements