

- 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
C++ Program to Find Largest Rectangular Area in a Histogram
This is a C++ Program to find largest Rectangular Area in a Histogram
Algorithmof function getArea():
Begin Create an empty stack. Initialize the largest_area. Do a while loop start from first bar for every bar hist[i], where i = 0 to less than n: If stack is empty or hist[i] is higher than the bar at top of stack, then push ‘i’ to stack. Else this bar is smaller than the top of stack, then keep removing the top of stack while top of the stack is greater. Calculate area of rectangle with smallest bar. Element before top in stack is left index and i is right index for the top. Pop the remaining bars from stack if stack is not empty and calculate area with every popped bar as the smallest bar. End
Example Code
#include<iostream> #include<stack> using namespace std; int getArea(int hist[], int n) { stack<int> st; int largest_area = 0; int top; int toparea; int i = 0; while (i < n) { if (st.empty() || hist[st.top()] <= hist[i]) st.push(i++); else { top = st.top(); st.pop(); toparea = hist[top] * (st.empty() ? i : i - st.top() - 1); if (largest_area < toparea) largest_area = toparea; } } while (st.empty() == false) { top = st.top(); st.pop(); toparea = hist[top] * (st.empty() ? i : i - st.top() - 1); if (largest_area < toparea) largest_area = toparea; } return largest_area; } int main() { int hist[] = {6,7,4,5,3,2}; int n = sizeof(hist)/sizeof(hist[0]); cout << "Largest area is " << getArea(hist, n); return 0; }
Output
Largest area is 16
- Related Questions & Answers
- Program to find largest rectangle area under histogram in python
- Find the largest area rectangular sub-matrix whose sum is equal to k in C++
- Program to find area of largest island in a matrix in Python
- Program to find a path a continuous path in a rectangular area without engaging a bomb in Python
- Program to find area of largest submatrix by column rearrangements in Python
- C++ program to find the Area of the Largest Triangle inscribed in a Hexagon?
- Program to find area of largest square of 1s in a given matrix in python
- Largest Rectangle in Histogram in Python
- Largest Triangle Area in Python
- Program to find area of a polygon in Python
- Python program to find largest number in a list
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- How to make a histogram with bins of equal area in Matplotlib?
- Find the area of largest circle inscribed in ellipse in C++
- Java program to find the area of a rectangle
Advertisements