Skip to content
Merged
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
44 changes: 44 additions & 0 deletions Arrays/LargestRectangleInHistogram.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <iostream>
#include <vector>

using namespace std;

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

int main() {
vector<int> array;

int number;

while (cin >> number) {
array.push_back(number);
}

cout << largestRectangleArea(array) << endl;

return 0;
}