smj007

Count subarrays with score less than K

Aug 10th, 2025 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. class Solution:
  2.     def countSubarrays(self, nums: List[int], k: int) -> int:
  3.        
  4.         prefix_sum = [0]*len(nums)
  5.         prefix_sum[0] = nums[0]
  6.         for i in range(1, len(nums)):
  7.             prefix_sum[i] = prefix_sum[i-1] + nums[i]
  8.  
  9.         # we will have a left and right pointer
  10.         left = 0
  11.         current_sum = 0
  12.         ans = 0
  13.  
  14.         def get_window_sum(left, right):
  15.             if left > right: return 0
  16.             return prefix_sum[right] - prefix_sum[left] + nums[left]
  17.  
  18.         for right in range(len(nums)):
  19.            
  20.             # first calculate the window sum
  21.             window_sum = get_window_sum(left, right)
  22.  
  23.             # keep reducing the window untill the window_sum*
  24.             while (right >= left and window_sum*(right-left+1)>=k):
  25.                 left += 1
  26.                 window_sum = get_window_sum(left, right)
  27.  
  28.             ans += right - left + 1
  29.  
  30. class Solution:
  31.     def countSubarrays(self, nums: List[int], k: int) -> int:
  32.        
  33.         # we will have a left and right pointer
  34.         left = 0
  35.         current_sum = 0
  36.         ans = 0
  37.  
  38.         for right in range(len(nums)):
  39.             current_sum += nums[right]
  40.  
  41.             # keep reducing the window untill the window_sum*
  42.             while (current_sum*(right - left + 1) >=k):
  43.                 current_sum -= nums[left]
  44.                 left += 1
  45.  
  46.             ans += right - left + 1
  47.  
  48.         return ans
  49.  
Advertisement
Add Comment
Please, Sign In to add comment