| | 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.SubarraysWithKDifferentIntegers; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SubarraysWithKDifferentIntegersSlidingWindow : ISubarraysWithKDifferentIntegers |
| | 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 SubarraysWithKDistinct(int[] nums, int k) |
| 2 | 25 | | { |
| 2 | 26 | | return AtMostKDistinct(nums, k) - AtMostKDistinct(nums, k - 1); |
| 2 | 27 | | } |
| | 28 | |
|
| | 29 | | private static int AtMostKDistinct(IReadOnlyList<int> nums, int k) |
| 4 | 30 | | { |
| 4 | 31 | | var result = 0; |
| | 32 | |
|
| 4 | 33 | | var left = 0; |
| | 34 | |
|
| 4 | 35 | | var numDictionary = new Dictionary<int, int>(); |
| | 36 | |
|
| 48 | 37 | | for (var right = 0; right < nums.Count; right++) |
| 20 | 38 | | { |
| 20 | 39 | | if (!numDictionary.TryAdd(nums[right], 1)) |
| 4 | 40 | | { |
| 4 | 41 | | numDictionary[nums[right]]++; |
| 4 | 42 | | } |
| | 43 | |
|
| 32 | 44 | | while (numDictionary.Count > k) |
| 12 | 45 | | { |
| 12 | 46 | | numDictionary[nums[left]]--; |
| | 47 | |
|
| 12 | 48 | | if (numDictionary[nums[left]] == 0) |
| 8 | 49 | | { |
| 8 | 50 | | numDictionary.Remove(nums[left]); |
| 8 | 51 | | } |
| | 52 | |
|
| 12 | 53 | | left++; |
| 12 | 54 | | } |
| | 55 | |
|
| 20 | 56 | | result += right - left + 1; |
| 20 | 57 | | } |
| | 58 | |
|
| 4 | 59 | | return result; |
| 4 | 60 | | } |
| | 61 | | } |