diff --git a/84-largest-rectangle-in-histogram/driver.cpp b/84-largest-rectangle-in-histogram/driver.cpp new file mode 100644 index 0000000..97dfd00 --- /dev/null +++ b/84-largest-rectangle-in-histogram/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + vector 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; +} \ No newline at end of file diff --git a/84-largest-rectangle-in-histogram/soln.cpp b/84-largest-rectangle-in-histogram/soln.cpp new file mode 100644 index 0000000..1b3da0a --- /dev/null +++ b/84-largest-rectangle-in-histogram/soln.cpp @@ -0,0 +1,57 @@ +#include "soln.hpp" + +int Solution::largestRectangleArea(vector &heights) +{ + if (heights.size() == 1) + { + return heights[0]; + } + stack> 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 &heights, int answer) +{ + return largestRectangleArea(heights) == answer; +} \ No newline at end of file diff --git a/84-largest-rectangle-in-histogram/soln.hpp b/84-largest-rectangle-in-histogram/soln.hpp new file mode 100644 index 0000000..f012994 --- /dev/null +++ b/84-largest-rectangle-in-histogram/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + int largestRectangleArea(vector& heights); + bool test(vector&heights, int answer); +}; \ No newline at end of file