K Radius Subarray Averages LeetCode solution in C++

1
class Solution {
2
public:
3
vector<int> getAverages(vector<int> &nums, int k) {
4
int n = nums.size();
5
int windowSize = 2 * k + 1;
6

7
long long windowSum = 0;
8
vector<int> result(n, -1);
9

10
if (n < windowSize) {
11
return result;
12
}
13

14
for (int i = 0; i < n; ++i) {
15
windowSum += nums[i]; // Add nums[i] to the window sum
16

17
if (i - windowSize >= 0) {
18
windowSum -= nums[i - windowSize]; // Remove nums[i - windowSize] from the window sum
19
}
20

21
if (i >= windowSize - 1) {
22
result[i - k] = windowSum / windowSize; // Calculate and store the average in the result
23
}
24
}
25

26
return result;
27
}
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0