RainX_69

Count Subarrays With Score Less Than K | OA LEVEL | TRICKY | MUST DO

Apr 15th, 2023
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | Software | 0 0
  1. https://leetcode.com/problems/count-subarrays-with-score-less-than-k/
  2.  
  3. The score of an array is defined as the product of its sum and its length.
  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. A subarray is a contiguous sequence of elements within an array.
  7.  
  8.  
  9. Example 1:
  10. Input: nums = [2,1,4,3,5], k = 10
  11. Output: 6
  12. Explanation:
  13. The 6 subarrays having scores less than 10 are:
  14. - [2] with score 2 * 1 = 2.
  15. - [1] with score 1 * 1 = 1.
  16. - [4] with score 4 * 1 = 4.
  17. - [3] with score 3 * 1 = 3.
  18. - [5] with score 5 * 1 = 5.
  19. - [2,1] with score (2 + 1) * 2 = 6.
  20. Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.
  21.  
  22. Example 2:
  23. Input: nums = [1,1,1], k = 5
  24. Output: 5
  25. Explanation:
  26. Every subarray except [1,1,1] has a score less than 5.
  27. [1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.
  28. Thus, there are 5 subarrays having scores less than 5.
  29.  
  30.  
  31. Constraints:
  32. 1 <= nums.length <= 10^5
  33. 1 <= nums[i] <= 10^5
  34. 1 <= k <= 10^15
  35.  
  36.  
  37. ------------------------------------------------------------------------------------------------------------------------------------
  38.  
  39. class Solution {
  40. public:
  41.     long long countSubarrays(vector<int>& nums, long long k) {
  42.         long long res=0;
  43.         int wS=0;
  44.         long long sum=0;
  45.         for(int wE=0;wE<nums.size();wE++){
  46.             sum+=nums[wE];
  47.             while(sum*(wE-wS+1)>=k){
  48.                 sum-=nums[wS++];
  49.             }
  50.             res+=(wE-wS+1);
  51.         }
  52.         return res;
  53.     }
  54. };
  55.  
  56. Can you do this using Binary Search??
Advertisement
Add Comment
Please, Sign In to add comment