Skip to content

2302. Count Subarrays With Score Less Than K 👍

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

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      sum += nums[r];
      while (sum * (r - l + 1) >= k)
        sum -= nums[l++];
      ans += r - l + 1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public long countSubarrays(int[] nums, long k) {
    long ans = 0;
    long sum = 0;

    for (int l = 0, r = 0; r < nums.length; ++r) {
      sum += nums[r];
      while (sum * (r - l + 1) >= k)
        sum -= nums[l++];
      ans += r - l + 1;
    }

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

    l = 0
    for r, num in enumerate(nums):
      summ += num
      while summ * (r - l + 1) >= k:
        summ -= nums[l]
        l += 1
      ans += r - l + 1

    return ans