Created
April 28, 2025 16:24
-
-
Save tatsuyax25/2f27b0b87b6cbb199a68ef0efbaa4be4 to your computer and use it in GitHub Desktop.
The score of an array is defined as the product of its sum and its length. For example, 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 subarrays of n
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @param {number} k | |
* @return {number} | |
*/ | |
var countSubarrays = function(nums, k) { | |
let left = 0; // Left pointer of the sliding window | |
let sum = 0; // Running sum of the current subarray | |
let result = 0; // Stores the count of valid subarrays | |
// Expand the window by moving the right pointer | |
for (let right = 0; right < nums.length; right++) { | |
sum += nums[right]; // Add the new element to the sum | |
// If the score of the current subarray (sum * length) is >= k, skrink the window | |
while (sum * (right - left + 1) >= k) { | |
sum -= nums[left]; // Remove the leftmost element | |
left++; // Move the left pointer forward | |
} | |
// The number of valid subarrays ending at 'right' is (right - left + 1) | |
result += (right - left + 1); | |
} | |
return result; // Return the total count of valid subarrays | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment