diff --git a/cpp/length-of-longest-subarray-with-at-most-k-frequency.cpp b/cpp/length-of-longest-subarray-with-at-most-k-frequency.cpp new file mode 100644 index 0000000..13ba7e0 --- /dev/null +++ b/cpp/length-of-longest-subarray-with-at-most-k-frequency.cpp @@ -0,0 +1,57 @@ +#include +#include + +class Solution { + public: + int maxSubarrayLength(const std::vector &nums, int k) { + auto n = nums.size(); + + std::unordered_map 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 + +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