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.
1import java.util.Arrays;
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 Arrays.fill(avgs, -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(String[] args) {
22 int[] nums = {7, 4, 3, 9, 1, 8, 5, 2, 6};
23 int k = 3;
24 int[] averages = getAverages(nums, k);
25
26 for (int avg : averages) {
27 System.out.print(avg + " ");
28 }
29 }
30}
The Java solution uses a simple nested loop to calculate averages by summing the k-radius subarray for each index where possible.
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.