1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00
LeetCode/cpp/length-of-longest-subarray-with-at-most-k-frequency.cpp
2024-03-29 00:11:12 +01:00

57 lines
1.1 KiB
C++

#include <unordered_map>
#include <vector>
class Solution {
public:
int maxSubarrayLength(const std::vector<int> &nums, int k) {
auto n = nums.size();
std::unordered_map<int, int> freqs;
int overshot = 0;
std::size_t i = 0, j;
for (j = 0; j < n; ++j) {
++freqs[nums[j]];
if (freqs[nums[j]] == k + 1) {
++overshot;
}
if (overshot > 0) {
--freqs[nums[i]];
if (freqs[nums[i]] == k) {
--overshot;
}
++i;
}
}
return n - i;
}
};
#ifdef _MF_TEST
#include <gtest/gtest.h>
TEST(examples, _1) {
Solution s;
EXPECT_EQ(s.maxSubarrayLength(std::vector{1, 2, 3, 1, 2, 3, 1, 2}, 2), 6);
}
TEST(examples, _2) {
Solution s;
EXPECT_EQ(s.maxSubarrayLength(std::vector{1, 2, 1, 2, 1, 2, 1, 2}, 1), 2);
}
TEST(examples, _3) {
Solution s;
EXPECT_EQ(s.maxSubarrayLength(std::vector{5, 5, 5, 5, 5, 5, 5}, 4), 4);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#endif