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.
1def getAverages(nums, k):
2 n = len(nums)
3 avgs = [-1] * n
4 sub_array_size = 2 * k + 1
5
6 for i in range(k, n - k):
7 total = 0
8 for j in range(i - k, i + k + 1):
9 total += nums[j]
10 avgs[i] = total // sub_array_size
11
12 return avgs
13
14nums = [7, 4, 3, 9, 1, 8, 5, 2, 6]
15k = 3
16print(getAverages(nums, k))
This Python solution follows a brute force pattern, using nested loops to sum the elements within the k-radius around each valid index, and sets -1 where not applicable.
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.