| | 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.MaximumAverageSubarray1; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximumAverageSubarray1SlidingWindow : IMaximumAverageSubarray1 |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public double FindMaxAverage(int[] nums, int k) |
| 3 | 25 | | { |
| 3 | 26 | | var maxAverage = double.MinValue; |
| | 27 | |
|
| 3 | 28 | | var left = 0; |
| | 29 | |
|
| 3 | 30 | | var average = 0.0; |
| | 31 | |
|
| 22 | 32 | | for (var right = 0; right < nums.Length; right++) |
| 8 | 33 | | { |
| 8 | 34 | | average += nums[right]; |
| | 35 | |
|
| 8 | 36 | | if (right - left + 1 > k) |
| 2 | 37 | | { |
| 2 | 38 | | average -= nums[left]; |
| | 39 | |
|
| 2 | 40 | | left++; |
| 2 | 41 | | } |
| | 42 | |
|
| 8 | 43 | | if (right - left + 1 == k) |
| 5 | 44 | | { |
| 5 | 45 | | maxAverage = Math.Max(maxAverage, average); |
| 5 | 46 | | } |
| 8 | 47 | | } |
| | 48 | |
|
| 3 | 49 | | return maxAverage / k; |
| 3 | 50 | | } |
| | 51 | | } |