Sponsored
Sponsored
The sliding window technique allows us to keep track of the sum of a subarray of fixed length k by adding one new element and removing the first element of the previous window, thus achieving O(n) time complexity.
Time Complexity: O(n)
Space Complexity: O(1)
1using System;
2
3public class Solution {
4 public double FindMaxAverage(int[] nums, int k) {
5 int sum = 0;
6 for (int i = 0; i < k; i++) {
7 sum += nums[i];
8 }
9 int maxSum = sum;
10 for (int i = k; i < nums.Length; i++) {
11 sum = sum - nums[i - k] + nums[i];
12 maxSum = Math.Max(maxSum, sum);
13 }
14 return (double) maxSum / k;
15 }
16 public static void Main(string[] args) {
17 Solution sol = new Solution();
18 int[] nums = {1, 12, -5, -6, 50, 3};
19 int k = 4;
20 Console.WriteLine(sol.FindMaxAverage(nums, k));
21 }
22}
The C# code maintains a running sum of the first k elements, then iterates over the array to update the sum as the window slides. It updates the maximum sum encountered and returns the average as a double.
The brute force approach involves checking every possible subarray of length k and calculating its average, then keeping track of the maximum average found. However, this approach is not efficient for large inputs.
Time Complexity: O(n*k)
Space Complexity: O(1)
1class
The Python brute force solution exhaustively checks all possible subarrays of length k, calculating the sum and average for each to find the maximum average. This approach is computationally expensive for higher values of n.