Skip to content

2090. K Radius Subarray Averages 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  vector<int> getAverages(vector<int>& nums, int k) {
    const int n = nums.size();
    const int size = 2 * k + 1;
    vector<int> ans(n, -1);
    if (size > n)
      return ans;

    long sum = accumulate(begin(nums), begin(nums) + size, 0L);

    for (int i = k; i + k < n; ++i) {
      ans[i] = sum / size;
      if (i + k + 1 < n)
        sum += nums[i + k + 1] - nums[i - k];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int[] getAverages(int[] nums, int k) {
    final int n = nums.length;
    final int size = 2 * k + 1;
    int[] ans = new int[n];
    Arrays.fill(ans, -1);
    if (size > n)
      return ans;

    long sum = 0;

    for (int i = 0; i < size; ++i)
      sum += nums[i];

    for (int i = k; i + k < n; ++i) {
      ans[i] = (int) (sum / size);
      if (i + k + 1 < n)
        sum += nums[i + k + 1] - nums[i - k];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def getAverages(self, nums: List[int], k: int) -> List[int]:
    n = len(nums)
    size = 2 * k + 1
    ans = [-1] * n
    if size > n:
      return ans

    summ = sum(nums[:size])

    for i in range(k, n - k):
      ans[i] = summ // size
      if i + k + 1 < n:
        summ += nums[i + k + 1] - nums[i - k]

    return ans