mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01: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:
parent
10e24a7593
commit
34f92878c2
1 changed files with 57 additions and 0 deletions
57
cpp/length-of-longest-subarray-with-at-most-k-frequency.cpp
Normal file
57
cpp/length-of-longest-subarray-with-at-most-k-frequency.cpp
Normal 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
|
Loading…
Reference in a new issue