From 34f92878c2550cb2958dd5726228d8881942f963 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 29 Mar 2024 00:11:12 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB2958.=20Length=20of=20Longes?= =?UTF-8?q?t=20Subarray=20With=20at=20Most=20K=20Frequency=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...gest-subarray-with-at-most-k-frequency.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 cpp/length-of-longest-subarray-with-at-most-k-frequency.cpp 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