snippets 0.1.0
Loading...
Searching...
No Matches
monotonic_stack.hpp
Go to the documentation of this file.
1#ifndef MONOTONIC_STACK_H
2#define MONOTONIC_STACK_H
3
4#include <iostream>
5#include <stack>
6#include <functional>
7#include <optional>
8#include <vector>
9
10namespace hsc_snippets {
16 template<typename T, typename Comparator>
18 private:
19 std::stack<T> s;
20 Comparator comp;
21
22 public:
28 std::optional<T> push(const T &value) {
29 while (!s.empty() && comp(s.top(), value)) {
30 s.pop();
31 }
32 std::optional<T> ans;
33 if (s.empty()) {
34 ans = {};
35 } else {
36 ans = s.top();
37 }
38 s.push(value);
39 return ans;
40 }
41
46 const T &top() const {
47 return s.top();
48 }
49
54 bool empty() const {
55 return s.empty();
56 }
57 };
58
59 template<typename T>
61 template<typename T>
63
71 template<typename T>
72 std::vector<T> nextGreaterElement(const std::vector<T> &nums, std::function<T()> no_greater) {
73 std::vector<T> result{};
74 result.reserve(nums.size());
75 MonotonicDecreasingStack<T> decreasingStack;
76 for (auto num: nums) {
77 auto tmp = decreasingStack.push(num);
78 if (!tmp.has_value()) {
79 result.push_back(no_greater());
80 } else {
81 result.push_back(tmp.value());
82 }
83 }
84
85 return result;
86 }
87
88
97 static int largestRectangleInHistogram(const std::vector<int> &heights) {
98 std::stack<int> s;
99 int maxArea = 0;
100 int n = static_cast<int>(heights.size());
101 for (int i = 0; i <= n; i++) {
102 int h = (i == n ? 0 : heights[i]); // Add a bar of height 0 to flush the stack at the end.
103 while (!s.empty() && h < heights[s.top()]) {
104 int height = heights[s.top()];
105 s.pop();
106 int width = s.empty() ? i : i - s.top() - 1; // Calculate width using the stack's new top.
107 maxArea = std::max(maxArea, height * width);
108 }
109 s.push(i); // Push the current index onto the stack.
110 }
111 return maxArea;
112 }
113}
114
115#endif // MONOTONIC_STACK_H
Definition monotonic_stack.hpp:17
std::optional< T > push(const T &value)
Definition monotonic_stack.hpp:28
bool empty() const
Definition monotonic_stack.hpp:54
const T & top() const
Definition monotonic_stack.hpp:46
Definition big_integer.hpp:14
std::vector< T > nextGreaterElement(const std::vector< T > &nums, std::function< T()> no_greater)
Definition monotonic_stack.hpp:72
static int largestRectangleInHistogram(const std::vector< int > &heights)
Definition monotonic_stack.hpp:97