mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 05:24:07 +00:00
day 36: 84-largest-rectangle-in-histogram
This commit is contained in:
parent
8ef205ad1e
commit
1168f54602
10
84-largest-rectangle-in-histogram/driver.cpp
Normal file
10
84-largest-rectangle-in-histogram/driver.cpp
Normal file
@ -0,0 +1,10 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> heights{2, 1, 5, 6, 2, 3};
|
||||
int answer = 10;
|
||||
Solution soln;
|
||||
cout << "Found largest rectangle area correctly? " << soln.test(heights, answer) << endl;
|
||||
return 0;
|
||||
}
|
||||
57
84-largest-rectangle-in-histogram/soln.cpp
Normal file
57
84-largest-rectangle-in-histogram/soln.cpp
Normal file
@ -0,0 +1,57 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int Solution::largestRectangleArea(vector<int> &heights)
|
||||
{
|
||||
if (heights.size() == 1)
|
||||
{
|
||||
return heights[0];
|
||||
}
|
||||
stack<pair<int, int>> stk;
|
||||
int max_area = 0, max_area_old;
|
||||
for (int i = 0; i < heights.size(); i++)
|
||||
{
|
||||
// empty stk, or increasing => push to stk
|
||||
// cout << i << " " << heights[i] << endl;
|
||||
if (stk.empty())
|
||||
{
|
||||
stk.push({i, heights[i]});
|
||||
// cout << "stack empty" << endl;
|
||||
}
|
||||
else if (heights[i] >= stk.top().second)
|
||||
{
|
||||
stk.push({i, heights[i]});
|
||||
// cout << "greater height, pushing" << endl;
|
||||
}
|
||||
// fun
|
||||
else
|
||||
{
|
||||
int new_top_index = i;
|
||||
// cout << "lower height" << endl;
|
||||
while (!stk.empty() && heights[i] < stk.top().second)
|
||||
{
|
||||
// cout << "popping " << stk.top().first << " " << stk.top().second << endl;
|
||||
max_area_old = (i - stk.top().first) * stk.top().second;
|
||||
max_area = max(max_area, max_area_old);
|
||||
new_top_index = stk.top().first;
|
||||
stk.pop();
|
||||
}
|
||||
stk.push({new_top_index, heights[i]});
|
||||
}
|
||||
// cout << "maxarea = " << max_area << endl;
|
||||
}
|
||||
|
||||
// cout << "non-empty stack at end, popping" << endl;
|
||||
while (!stk.empty())
|
||||
{
|
||||
// cout << stk.top().first << " " << stk.top().second << endl;
|
||||
max_area_old = (heights.size() - stk.top().first) * stk.top().second;
|
||||
max_area = max(max_area, max_area_old);
|
||||
stk.pop();
|
||||
}
|
||||
return max_area;
|
||||
}
|
||||
|
||||
bool Solution::test(vector<int> &heights, int answer)
|
||||
{
|
||||
return largestRectangleArea(heights) == answer;
|
||||
}
|
||||
8
84-largest-rectangle-in-histogram/soln.hpp
Normal file
8
84-largest-rectangle-in-histogram/soln.hpp
Normal file
@ -0,0 +1,8 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
int largestRectangleArea(vector<int>& heights);
|
||||
bool test(vector<int>&heights, int answer);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user