snippets 0.1.0
Loading...
Searching...
No Matches
sliding_window.hpp
Go to the documentation of this file.
1#ifndef SLIDING_WINDOW_H
2#define SLIDING_WINDOW_H
3
4#include <concepts>
5#include <deque>
6#include <optional>
7#include <vector>
8#include <unordered_map>
9
10namespace hsc_snippets {
11
12 template<std::integral T>
14 public:
18 explicit SlidingWindowMax(size_t size) : maxSize(size) {}
19
24 void update(T value) {
25 // Remove the front element if it's outside the window's range
26 while (!window.empty() && window.front().second <= currentIndex - static_cast<int>(maxSize)) {
27 window.pop_front();
28 }
29
30 // Remove elements from the back that are smaller than the new element
31 while (!window.empty() && value >= window.back().first) {
32 window.pop_back();
33 }
34
35 // Add the new element to the back
36 window.push_back(std::make_pair(value, currentIndex));
37
38 currentIndex += 1;
39 }
40
45 std::optional<T> get_max() const {
46 if (window.empty()) {
47 return std::nullopt; // Return an empty optional if the window is empty
48 }
49 return window.front().first; // The front always holds the maximum value
50 }
51
56 size_t size() const {
57 return std::min(maxSize, static_cast<size_t>(currentIndex -
58 (window.empty() ? currentIndex : window.front().second)));
59 }
60
61 private:
62 std::deque<std::pair<T, int>> window; // Pair of value and its index
63 size_t maxSize;
64 int currentIndex = 0; // To keep track of the index of the latest element added
65 };
66
76 static int subarraysWithAtMostKDistinct(const std::vector<int> &nums, int k) {
77 const int n = static_cast<int>(nums.size());
78 std::unordered_map<int, int> m;
79 int ans = 0;
80 int left = 0;
81 int right = 0;
82
83 while (right < n) {
84 m[nums[right]]++;
85
86 while (left <= right && m.size() > k) {
87 if (auto it = m.find(nums[left]); it->second == 1) {
88 m.erase(it);
89 } else {
90 it->second -= 1;
91 }
92 left++;
93 }
94
95 ans += (right - left + 1);
96
97 right++;
98 }
99
100 return ans;
101 }
102}
103
104#endif // SLIDING_WINDOW_H
Definition sliding_window.hpp:13
SlidingWindowMax(size_t size)
Definition sliding_window.hpp:18
size_t size() const
Definition sliding_window.hpp:56
std::optional< T > get_max() const
Definition sliding_window.hpp:45
void update(T value)
Definition sliding_window.hpp:24
Definition big_integer.hpp:14
static int subarraysWithAtMostKDistinct(const std::vector< int > &nums, int k)
Definition sliding_window.hpp:76