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

TC = O(n) single pass, SC = O(n) #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
43 changes: 43 additions & 0 deletions LargestRectangleInHistogram.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//TC = O(n) single pass
//SC = o(n)
#include <bits/stdc++.h>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
#define ll long long
#define IOS ios_base::sync_with_stdio(false);
#define print(array) \
for (auto it : array) \
cout << it << " "
#define sortit(array) sort(array.begin(), array.end())
const int M = 1e9 + 7;

int largestRectangleArea(vector<int> &heights)
{
stack<int> st;
int maxarea = 0;
int width = 0;
int n = heights.size();
for (int i = 0; i <= n; i++)
{
while (!st.empty() && (i == n || heights[st.top()] >= heights[i]))
{
int height = heights[st.top()];
st.pop();
if (st.empty())
width = i;
else
width = i - st.top() - 1;
maxarea = max(maxarea, width * height);
}
st.push(i);
}
return maxarea;
}

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