Sponsored
Sponsored
This approach involves iterating over each element in the array and calculating the subarray sum for each index considering the radius. If there is an insufficient number of elements, return -1 for that index. The average is computed using integer division.
Time Complexity: O(n*k), where n is the size of the array.
Space Complexity: O(n), for the output array.
1using System;
2
3public class SubarrayAverages {
4 public static int[] GetAverages(int[] nums, int k) {
5 int n = nums.Length;
6 int[] avgs = new int[n];
7 for (int i = 0; i < n; i++) avgs[i] = -1;
8 int subArraySize = 2 * k + 1;
9
10 for (int i = k; i < n - k; i++) {
11 long sum = 0;
12 for (int j = i - k; j <= i + k; j++) {
13 sum += nums[j];
14 }
15 avgs[i] = (int)(sum / subArraySize);
16 }
17
18 return avgs;
19 }
20
21 public static void Main() {
22 int[] nums = {7, 4, 3, 9, 1, 8, 5, 2, 6};
23 int k = 3;
24 int[] averages = GetAverages(nums, k);
25 Console.WriteLine(string.Join(" ", averages));
26 }
27}
In this C# implementation, a brute force approach is adopted with a nested loop calculated sum for averaging where the subarray size is sufficient.
The sliding window approach helps optimize the brute force method by avoiding redundant calculations when sums overlap, significantly reducing the time complexity.
Time Complexity: O(n), as each element is added and removed from the sum at most once.
Space Complexity: O(n), for storing the results.
1import
This Java implementation effectively uses sliding window optimization to keep a running total sum for the needed window range, achieving linear time complexity.