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.
1#include <vector>
#include <iostream>
std::vector<int> getAverages(std::vector<int>& nums, int k) {
int n = nums.size();
std::vector<int> avgs(n, -1);
int subArraySize = 2 * k + 1;
long long windowSum = 0;
for (int i = 0; i < n; ++i) {
windowSum += nums[i];
if (i >= subArraySize) {
windowSum -= nums[i - subArraySize];
}
if (i >= subArraySize - 1) {
avgs[i - k] = windowSum / subArraySize;
}
}
return avgs;
}
int main() {
std::vector<int> nums = {7, 4, 3, 9, 1, 8, 5, 2, 6};
int k = 3;
std::vector<int> averages = getAverages(nums, k);
for (auto avg : averages) {
std::cout << avg << " ";
}
return 0;
}
The C++ implementation uses a sliding window technique, maintaining a running sum by adding the new element and subtracting the old one beyond the window size.