Skip to content

Add soulution for problem 084 Largest Rectangle in Histogram #49

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

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
51 changes: 51 additions & 0 deletions C++/084_Largest_Rectangle_in_Histogram.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//84. Largest Rectangle in Histogram
/*
*Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
*
*
*Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
*
*
*The largest rectangle is shown in the shaded area, which has area = 10 unit.
*
*For example,
*Given heights = [2,1,5,6,2,3],
*return 10.
*
*Tag: Array, Stack
*
*Author: Linsen Wu
*/

#include "stdafx.h"
#include <vector>
#include <stack>

using namespace std;

class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> MtSt;
heights.push_back(0);
int sum = 0;
for (int i = 0; i < heights.size(); i++) {
if (MtSt.empty() || heights[i] > heights[MtSt.top()]) {
MtSt.push(i);
}
else {
int tmp = MtSt.top();
MtSt.pop();
sum = max(sum, heights[tmp]*(MtSt.empty()? i : i-MtSt.top()-1));
i--;
}
}
return sum;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}