Skip to content

1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int numOfSubarrays(vector<int>& arr, int k, int threshold) {
    int ans = 0;
    int windowSum = 0;

    for (int i = 0; i < arr.size(); ++i) {
      windowSum += arr[i];
      if (i >= k)
        windowSum -= arr[i - k];
      if (i >= k - 1 && windowSum / k >= threshold)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int numOfSubarrays(int[] arr, int k, int threshold) {
    int ans = 0;
    int windowSum = 0;

    for (int i = 0; i < arr.length; ++i) {
      windowSum += arr[i];
      if (i >= k)
        windowSum -= arr[i - k];
      if (i >= k - 1 && windowSum / k >= threshold)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def numOfSubarrays(self, arr: list[int], k: int, threshold: int) -> int:
    ans = 0
    windowSum = 0

    for i in range(len(arr)):
      windowSum += arr[i]
      if i >= k:
        windowSum -= arr[i - k]
      if i >= k - 1 and windowSum // k >= threshold:
        ans += 1

    return ans