Skip to content

Commit f13be20

Browse files
Merge pull request #107 from Amit-yadav099/main
added solution of <largest rectangle in histogram>#104
2 parents 5ac3f31 + cee5aa3 commit f13be20

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//code link https://leetcode.com/problems/largest-rectangle-in-histogram/
2+
3+
#include<bits/stdc++.h>
4+
using namespace std;
5+
6+
//this problem demonstrates the best implementation of the stack
7+
class Solution {
8+
public:
9+
int largestRectangleArea(vector<int>& height) {
10+
int n=height.size();
11+
vector<int>right(n,n);
12+
vector<int>left(n,-1);
13+
stack<int>st;
14+
//for Next samllest right(NSR)
15+
for(int i=0;i<n;i++){
16+
while(!st.empty()&& height[st.top()]>height[i]){
17+
right[st.top()]=i;
18+
st.pop();
19+
}
20+
st.push(i);
21+
}
22+
23+
//for Next smallest left(NSL)
24+
for(int i=n-1;i>=0;i--){
25+
while(!st.empty() && height[st.top()]>height[i]){
26+
left[st.top()]=i;
27+
st.pop();
28+
}
29+
st.push(i);
30+
}
31+
int ans=0;
32+
// maximum height for the given index is the (NSR-NSL-1)
33+
for(int i=0;i<n;i++){
34+
ans=max(ans,height[i]*(right[i]-left[i]-1));
35+
}
36+
return ans;
37+
}
38+
39+
};

0 commit comments

Comments
 (0)