| | 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.MaximumSumOfDistinctSubarraysWithLengthK; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximumSumOfDistinctSubarraysWithLengthKSlidingWindow : IMaximumSumOfDistinctSubarraysWithLengthK |
| | 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 long MaximumSubarraySum(int[] nums, int k) |
| 2 | 25 | | { |
| 2 | 26 | | long maxSum = 0; |
| 2 | 27 | | long currentSum = 0; |
| 2 | 28 | | var hashSet = new HashSet<int>(); |
| | 29 | |
|
| 2 | 30 | | var left = 0; |
| | 31 | |
|
| 24 | 32 | | for (var right = 0; right < nums.Length; right++) |
| 10 | 33 | | { |
| 15 | 34 | | while (hashSet.Contains(nums[right])) |
| 5 | 35 | | { |
| 5 | 36 | | hashSet.Remove(nums[left]); |
| 5 | 37 | | currentSum -= nums[left]; |
| | 38 | |
|
| 5 | 39 | | left++; |
| 5 | 40 | | } |
| | 41 | |
|
| 10 | 42 | | hashSet.Add(nums[right]); |
| 10 | 43 | | currentSum += nums[right]; |
| | 44 | |
|
| 10 | 45 | | if (right - left + 1 != k) |
| 7 | 46 | | { |
| 7 | 47 | | continue; |
| | 48 | | } |
| | 49 | |
|
| 3 | 50 | | maxSum = Math.Max(maxSum, currentSum); |
| | 51 | |
|
| 3 | 52 | | hashSet.Remove(nums[left]); |
| 3 | 53 | | currentSum -= nums[left]; |
| | 54 | |
|
| 3 | 55 | | left++; |
| 3 | 56 | | } |
| | 57 | |
|
| 2 | 58 | | return maxSum; |
| 2 | 59 | | } |
| | 60 | | } |