| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.CountSubarraysWithFixedBounds; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class CountSubarraysWithFixedBoundsSlidingWindow : ICountSubarraysWithFixedBounds |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n) |
| | | 19 | | /// Space complexity - O(1) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <param name="minK"></param> |
| | | 23 | | /// <param name="maxK"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public long CountSubarrays(int[] nums, int minK, int maxK) |
| | 2 | 26 | | { |
| | 2 | 27 | | long count = 0; |
| | | 28 | | |
| | 2 | 29 | | var lastMinKPosition = -1; |
| | 2 | 30 | | var lastMaxKPosition = -1; |
| | | 31 | | |
| | 2 | 32 | | var left = 0; |
| | | 33 | | |
| | 24 | 34 | | for (var right = 0; right < nums.Length; right++) |
| | 10 | 35 | | { |
| | 10 | 36 | | if (nums[right] == minK) |
| | 5 | 37 | | { |
| | 5 | 38 | | lastMinKPosition = right; |
| | 5 | 39 | | } |
| | | 40 | | |
| | 10 | 41 | | if (nums[right] == maxK) |
| | 6 | 42 | | { |
| | 6 | 43 | | lastMaxKPosition = right; |
| | 6 | 44 | | } |
| | | 45 | | |
| | 10 | 46 | | if (nums[right] < minK || nums[right] > maxK) |
| | 1 | 47 | | { |
| | 1 | 48 | | left = right + 1; |
| | 1 | 49 | | } |
| | | 50 | | |
| | 10 | 51 | | if (lastMinKPosition != -1 && lastMaxKPosition != -1) |
| | 8 | 52 | | { |
| | 8 | 53 | | count += Math.Max(0, Math.Min(lastMinKPosition, lastMaxKPosition) - left + 1); |
| | 8 | 54 | | } |
| | 10 | 55 | | } |
| | | 56 | | |
| | 2 | 57 | | return count; |
| | 2 | 58 | | } |
| | | 59 | | } |