- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- 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 Articles
- Largest Rectangle in Histogram in Python
- C++ Program to Find Largest Rectangular Area in a Histogram
- Program to find area of largest island in a matrix in Python
- Python Program to Find the Area of a Rectangle Using Classes
- Program to find area of largest submatrix by column rearrangements in Python
- Java program to find the area of a rectangle
- Swift Program to find the area of the rectangle
- Golang program to find the area of a rectangle
- Area of largest triangle that can be inscribed within a rectangle in C Program?
- Program to find area of largest square of 1s in a given matrix in python
- Area of Largest rectangle that can be inscribed in an Ellipse?
- Largest Triangle Area in Python
- Golang Program to Find the Area of a Rectangle Using Classes
- Python Program to find largest element in an array
- Python program to find largest number in a list

Advertisements