34f92878c2
Signed-off-by: Matej Focko <me@mfocko.xyz>
57 lines
1.1 KiB
C++
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
|