| | 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.ContinuousSubarrays; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ContinuousSubarraysTwoPointers : IContinuousSubarrays |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public long ContinuousSubarrays(int[] nums) |
| 2 | 24 | | { |
| 2 | 25 | | long result = 0; |
| | 26 | |
|
| 2 | 27 | | var left = 0; |
| 2 | 28 | | var right = 0; |
| | 29 | |
|
| | 30 | | long windowLength; |
| | 31 | |
|
| 2 | 32 | | var currentMin = nums[right]; |
| 2 | 33 | | var currentMax = nums[right]; |
| | 34 | |
|
| 18 | 35 | | for (right = 0; right < nums.Length; right++) |
| 7 | 36 | | { |
| 7 | 37 | | currentMin = Math.Min(currentMin, nums[right]); |
| 7 | 38 | | currentMax = Math.Max(currentMax, nums[right]); |
| | 39 | |
|
| 7 | 40 | | if (currentMax - currentMin <= 2) |
| 6 | 41 | | { |
| 6 | 42 | | continue; |
| | 43 | | } |
| | 44 | |
|
| 1 | 45 | | windowLength = right - left; |
| 1 | 46 | | result += windowLength * (windowLength + 1) / 2; |
| | 47 | |
|
| 1 | 48 | | left = right; |
| 1 | 49 | | currentMin = currentMax = nums[right]; |
| | 50 | |
|
| 2 | 51 | | while (left > 0 && Math.Abs(nums[right] - nums[left - 1]) <= 2) |
| 1 | 52 | | { |
| 1 | 53 | | left--; |
| | 54 | |
|
| 1 | 55 | | currentMin = Math.Min(currentMin, nums[left]); |
| 1 | 56 | | currentMax = Math.Max(currentMax, nums[left]); |
| 1 | 57 | | } |
| | 58 | |
|
| 1 | 59 | | if (left >= right) |
| 0 | 60 | | { |
| 0 | 61 | | continue; |
| | 62 | | } |
| | 63 | |
|
| 1 | 64 | | windowLength = right - left; |
| 1 | 65 | | result -= windowLength * (windowLength + 1) / 2; |
| 1 | 66 | | } |
| | 67 | |
|
| 2 | 68 | | windowLength = right - left; |
| 2 | 69 | | result += windowLength * (windowLength + 1) / 2; |
| | 70 | |
|
| 2 | 71 | | return result; |
| 2 | 72 | | } |
| | 73 | | } |