1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 01:36:57 +02:00

cpp: add «2958. Length of Longest Subarray With at Most K Frequency»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-03-29 00:11:12 +01:00
parent 10e24a7593
commit 34f92878c2
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,57 @@
#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