Advertisement
hoangreal

Count Subarrays With Score Less Than K

Oct 19th, 2024 (edited)
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | Source Code | 0 0
  1. """
  2. The score of an array is defined as the product of its sum and its length.
  3.  
  4. For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.
  5. Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k.
  6.  
  7. A subarray is a contiguous sequence of elements within an array.
  8. """
  9. class Solution:
  10.     def countSubarrays(self, nums: List[int], k: int) -> int:
  11.         answer = 0
  12.  
  13.         left_i = 0; total = 0; right_i = 0
  14.         while right_i < len(nums):
  15.             total += nums[right_i]
  16.             while True:
  17.                 if left_i > right_i:
  18.                     break
  19.                
  20.                 if total * (right_i - left_i + 1) < k:
  21.                     break
  22.                
  23.                 total -= nums[left_i]
  24.                 left_i += 1
  25.            
  26.             if left_i > right_i:
  27.                 right_i = left_i
  28.             else:
  29.                 answer = answer + (right_i - left_i + 1)
  30.                 right_i += 1
  31.  
  32.         return answer
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement