Skip to content

Commit

Permalink
Merge pull request #107 from Amit-yadav099/main
Browse files Browse the repository at this point in the history
added solution of <largest rectangle in histogram>#104
  • Loading branch information
Pradeepsingh61 authored Oct 17, 2024
2 parents 5ac3f31 + cee5aa3 commit f13be20
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions C++/C++ Programs/maximumRectangleInHistrogram.cpp
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;
}

};

0 comments on commit f13be20

Please sign in to comment.