2302. Count Subarrays With Score Less Than K #1617
-
Topics: The score of an array is defined as the product of its sum and its length.
Given a positive integer array A subarray is a contiguous sequence of elements within an array. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of non-empty subarrays of a given array whose score (defined as the product of the subarray's sum and its length) is strictly less than a given integer k. Given the constraints, an efficient approach is necessary to avoid a brute-force solution. ApproachThe key insight here is that for a given starting index i, the score of the subarray starting at i and ending at j increases as j increases. This allows us to use a binary search approach to efficiently determine the maximum valid j for each starting index i.
Let's implement this solution in PHP: 2302. Count Subarrays With Score Less Than K <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function countSubarrays($nums, $k) {
$n = count($nums);
$prefix = array_fill(0, $n + 1, 0);
for ($i = 0; $i < $n; $i++) {
$prefix[$i + 1] = $prefix[$i] + $nums[$i];
}
$count = 0;
for ($i = 0; $i < $n; $i++) {
$low = $i;
$high = $n - 1;
$best_j = -1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
$sum = $prefix[$mid + 1] - $prefix[$i];
$length = $mid - $i + 1;
$product = $sum * $length;
if ($product < $k) {
$best_j = $mid;
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
if ($best_j != -1) {
$count += ($best_j - $i + 1);
}
}
return $count;
}
// Example 1
$nums = [2, 1, 4, 3, 5];
$k = 10;
echo countSubarrays($nums, $k) . "\n"; // Output: 6
// Example 2
$nums = [1, 1, 1];
$k = 5;
echo countSubarrays($nums, $k) . "\n"; // Output: 5
?> Explanation:
This approach ensures that we efficiently count all valid subarrays in O(n log n) time, making it suitable for large input sizes up to 105. |
Beta Was this translation helpful? Give feedback.
We need to count the number of non-empty subarrays of a given array whose score (defined as the product of the subarray's sum and its length) is strictly less than a given integer k. Given the constraints, an efficient approach is necessary to avoid a brute-force solution.
Approach
The key insight here is that for a given starting index i, the score of the subarray starting at i and ending at j increases as j increases. This allows us to use a binary search approach to efficiently determine the maximum valid j for each starting index i.