| | 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.CountTheNumberOfGoodSubarrays; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountTheNumberOfGoodSubarraysTwoPointers : ICountTheNumberOfGoodSubarrays |
| | 16 | | { |
| | 17 | | public long CountGood(int[] nums, int k) |
| 2 | 18 | | { |
| 2 | 19 | | long result = 0; |
| | 20 | |
|
| 2 | 21 | | var frequencyDictionary = new Dictionary<int, int>(); |
| | 22 | |
|
| 2 | 23 | | var pairsCount = 0; |
| 2 | 24 | | var left = 0; |
| | 25 | |
|
| 28 | 26 | | for (var right = 0; right < nums.Length; right++) |
| 12 | 27 | | { |
| 12 | 28 | | if (!frequencyDictionary.TryAdd(nums[right], 1)) |
| 7 | 29 | | { |
| 7 | 30 | | pairsCount += frequencyDictionary[nums[right]]; |
| | 31 | |
|
| 7 | 32 | | frequencyDictionary[nums[right]]++; |
| 7 | 33 | | } |
| | 34 | |
|
| 16 | 35 | | while (pairsCount >= k && left <= right) |
| 4 | 36 | | { |
| 4 | 37 | | result += nums.Length - right; |
| | 38 | |
|
| 4 | 39 | | frequencyDictionary[nums[left]]--; |
| | 40 | |
|
| 4 | 41 | | pairsCount -= frequencyDictionary[nums[left]]; |
| | 42 | |
|
| 4 | 43 | | left++; |
| 4 | 44 | | } |
| 12 | 45 | | } |
| | 46 | |
|
| 2 | 47 | | return result; |
| 2 | 48 | | } |
| | 49 | | } |