day 36: 84-largest-rectangle-in-histogram

This commit is contained in:
Kaushik Narayan R 2023-11-09 08:44:53 -07:00
parent 8ef205ad1e
commit 1168f54602
3 changed files with 75 additions and 0 deletions

View 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;
}

View 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;
}

View 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);
};