Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the largest rectangle in histogram problem #29

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Uncategorized/Largest Rectangle In Histogram/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Largest Rectangle In Histogram

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

## Example:
![plot](./histogram.jpg?raw=true)

Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions Uncategorized/Largest Rectangle In Histogram/largest.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

vector<int> nearestSmallerOnRight(vector<int>& heights) {
stack<int>st;
vector<int>ans(heights.size(),heights.size());
for(int i=0;i<heights.size();i++)
{
while(!st.empty() && heights[i]<heights[st.top()])
{
ans[st.top()]=i;
st.pop();
}
st.push(i);
}
return ans;
}

vector<int> nearestSmallerOnLeft(vector<int>& heights)
{
stack<int>st;
vector<int>ans(heights.size(),-1);
for(int i=heights.size()-1;i>=0;i--)
{
while(!st.empty() && heights[i]<heights[st.top()])
{
ans[st.top()]=i;
st.pop();
}
st.push(i);
}
return ans;
}

int largestRectangleArea(vector<int>& heights)
{
vector<int>NSR=nearestSmallerOnRight(heights);
vector<int>NSL=nearestSmallerOnLeft(heights);
int ans=0;
for(int i=0;i<heights.size();i++)
ans=max(ans,(NSR[i]-NSL[i]-1)*heights[i]);
return ans;
}

int main() {
vector<int> vec = {2, 1, 5, 6, 2, 3};
cout << largestRectangleArea(vec);
}