Count Subarrays With Score Less Than K

hard sliding window two pointers subarray

Problem

The score of an array is its sum multiplied by its length — e.g. the score of [1,2,3,4,5] is (1+2+3+4+5)·5 = 75. Given a positive integer array nums and an integer k, return the number of non-empty contiguous subarrays whose score is strictly less than k.

Inputnums = [2,1,4,3,5], k = 10
Output6
The 6 good subarrays are [2], [1], [4], [3], [5] (each length 1) and [2,1] with score (2+1)·2 = 6. [1,4] scores 10 and [4,3,5] scores 36, both excluded.
Inputnums = [1,1,1], k = 5
Output5
Every subarray except [1,1,1] qualifies; [1,1,1] scores (1+1+1)·3 = 9 ≥ 5.

def count_subarrays(nums, k):
    ans = 0
    total = 0
    left = 0
    for right in range(len(nums)):
        total += nums[right]
        while total * (right - left + 1) >= k:
            total -= nums[left]
            left += 1
        ans += right - left + 1
    return ans
function countSubarrays(nums, k) {
  let ans = 0, total = 0, left = 0;
  for (let right = 0; right < nums.length; right++) {
    total += nums[right];
    while (total * (right - left + 1) >= k) {
      total -= nums[left];
      left++;
    }
    ans += right - left + 1;
  }
  return ans;
}
long countSubarrays(int[] nums, long k) {
    long ans = 0, total = 0;
    int left = 0;
    for (int right = 0; right < nums.length; right++) {
        total += nums[right];
        while (total * (right - left + 1) >= k) {
            total -= nums[left];
            left++;
        }
        ans += right - left + 1;
    }
    return ans;
}
long long countSubarrays(vector<int>& nums, long long k) {
    long long ans = 0, total = 0;
    int left = 0;
    for (int right = 0; right < (int)nums.size(); right++) {
        total += nums[right];
        while (total * (right - left + 1) >= k) {
            total -= nums[left];
            left++;
        }
        ans += right - left + 1;
    }
    return ans;
}
Time: O(n) Space: O(1)