-
Notifications
You must be signed in to change notification settings - Fork 69
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #107 from Amit-yadav099/main
added solution of <largest rectangle in histogram>#104
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
//code link https://leetcode.com/problems/largest-rectangle-in-histogram/ | ||
|
||
#include<bits/stdc++.h> | ||
using namespace std; | ||
|
||
//this problem demonstrates the best implementation of the stack | ||
class Solution { | ||
public: | ||
int largestRectangleArea(vector<int>& height) { | ||
int n=height.size(); | ||
vector<int>right(n,n); | ||
vector<int>left(n,-1); | ||
stack<int>st; | ||
//for Next samllest right(NSR) | ||
for(int i=0;i<n;i++){ | ||
while(!st.empty()&& height[st.top()]>height[i]){ | ||
right[st.top()]=i; | ||
st.pop(); | ||
} | ||
st.push(i); | ||
} | ||
|
||
//for Next smallest left(NSL) | ||
for(int i=n-1;i>=0;i--){ | ||
while(!st.empty() && height[st.top()]>height[i]){ | ||
left[st.top()]=i; | ||
st.pop(); | ||
} | ||
st.push(i); | ||
} | ||
int ans=0; | ||
// maximum height for the given index is the (NSR-NSL-1) | ||
for(int i=0;i<n;i++){ | ||
ans=max(ans,height[i]*(right[i]-left[i]-1)); | ||
} | ||
return ans; | ||
} | ||
|
||
}; |