| | 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.CountSubarraysWhereMaxElementAppearsAtLeastKTimes; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountSubarraysWhereMaxElementAppearsAtLeastKTimesSlidingWindow : |
| | 16 | | ICountSubarraysWhereMaxElementAppearsAtLeastKTimes |
| | 17 | | { |
| | 18 | | /// <summary> |
| | 19 | | /// Time complexity - O(n) |
| | 20 | | /// Space complexity - O(1) |
| | 21 | | /// </summary> |
| | 22 | | /// <param name="nums"></param> |
| | 23 | | /// <param name="k"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public long CountSubarrays(int[] nums, int k) |
| 2 | 26 | | { |
| 2 | 27 | | var maxElement = nums.Max(); |
| | 28 | |
|
| 2 | 29 | | var count = 0; |
| 2 | 30 | | var start = 0; |
| 2 | 31 | | var maxElementsInWindow = 0; |
| | 32 | |
|
| 24 | 33 | | foreach (var num in nums) |
| 9 | 34 | | { |
| 9 | 35 | | if (num == maxElement) |
| 4 | 36 | | { |
| 4 | 37 | | maxElementsInWindow++; |
| 4 | 38 | | } |
| | 39 | |
|
| 13 | 40 | | while (k == maxElementsInWindow) |
| 4 | 41 | | { |
| 4 | 42 | | if (nums[start] == maxElement) |
| 2 | 43 | | { |
| 2 | 44 | | maxElementsInWindow--; |
| 2 | 45 | | } |
| | 46 | |
|
| 4 | 47 | | start++; |
| 4 | 48 | | } |
| | 49 | |
|
| 9 | 50 | | count += start; |
| 9 | 51 | | } |
| | 52 | |
|
| 2 | 53 | | return count; |
| 2 | 54 | | } |
| | 55 | | } |