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.
1#include <vector>
2#include <iostream>
3
4std::vector<int> getAverages(std::vector<int>& nums, int k) {
5 int n = nums.size();
6 std::vector<int> avgs(n, -1);
7 int subArraySize = 2 * k + 1;
8
9 for (int i = k; i < n - k; ++i) {
10 long sum = 0;
11 for (int j = i - k; j <= i + k; ++j) {
12 sum += nums[j];
13 }
14 avgs[i] = sum / subArraySize;
15 }
16
17 return avgs;
18}
19
20int main() {
21 std::vector<int> nums = {7, 4, 3, 9, 1, 8, 5, 2, 6};
22 int k = 3;
23 std::vector<int> averages = getAverages(nums, k);
24
25 for (auto avg : averages) {
26 std::cout << avg << " ";
27 }
28 return 0;
29}
This C++ solution also implements a brute force method where the sum for each index's subarray is calculated directly, excluding indices where a complete k-radius subarray isn't 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.