| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.LengthOfLongestSubarrayWithAtMostKFrequency; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LengthOfLongestSubarrayWithAtMostKFrequencyTwoPointers : ILengthOfLongestSubarrayWithAtMostKFrequency |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int MaxSubarrayLength(int[] nums, int k) |
| 15 | 25 | | { |
| 15 | 26 | | var maxLength = 0; |
| 15 | 27 | | var left = 0; |
| | 28 | |
|
| 15 | 29 | | var frequencyDictionary = new Dictionary<int, int>(); |
| | 30 | |
|
| 222 | 31 | | for (var right = 0; right < nums.Length; right++) |
| 96 | 32 | | { |
| 96 | 33 | | if (frequencyDictionary.TryGetValue(nums[right], out var value)) |
| 48 | 34 | | { |
| 48 | 35 | | frequencyDictionary[nums[right]] = ++value; |
| 48 | 36 | | } |
| | 37 | | else |
| 48 | 38 | | { |
| 48 | 39 | | frequencyDictionary[nums[right]] = 1; |
| 48 | 40 | | } |
| | 41 | |
|
| 129 | 42 | | while (frequencyDictionary[nums[right]] > k) |
| 33 | 43 | | { |
| 33 | 44 | | frequencyDictionary[nums[left]]--; |
| | 45 | |
|
| 33 | 46 | | if (frequencyDictionary[nums[left]] == 0) |
| 7 | 47 | | { |
| 7 | 48 | | frequencyDictionary.Remove(nums[left]); |
| 7 | 49 | | } |
| | 50 | |
|
| 33 | 51 | | left++; |
| 33 | 52 | | } |
| | 53 | |
|
| 96 | 54 | | maxLength = Math.Max(maxLength, right - left + 1); |
| 96 | 55 | | } |
| | 56 | |
|
| 15 | 57 | | return maxLength; |
| 15 | 58 | | } |
| | 59 | | } |