|
| 1 | +# 2302. Count Subarrays With Score Less Than K |
| 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 | + |
| 6 | +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`. |
| 7 | + |
| 8 | +A **subarray** is a contiguous sequence of elements within an array. |
| 9 | + |
| 10 | +#### Example 1: |
| 11 | +<pre> |
| 12 | +<strong>Input:</strong> nums = [2,1,4,3,5], k = 10 |
| 13 | +<strong>Output:</strong> 6 |
| 14 | +<strong>Explanation:</strong> |
| 15 | +The 6 subarrays having scores less than 10 are: |
| 16 | +- [2] with score 2 * 1 = 2. |
| 17 | +- [1] with score 1 * 1 = 1. |
| 18 | +- [4] with score 4 * 1 = 4. |
| 19 | +- [3] with score 3 * 1 = 3. |
| 20 | +- [5] with score 5 * 1 = 5. |
| 21 | +- [2,1] with score (2 + 1) * 2 = 6. |
| 22 | +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. |
| 23 | +</pre> |
| 24 | + |
| 25 | +#### Example 2: |
| 26 | +<pre> |
| 27 | +<strong>Input:</strong> nums = [1,1,1], k = 5 |
| 28 | +<strong>Output:</strong> 5 |
| 29 | +<strong>Explanation:</strong> |
| 30 | +Every subarray except [1,1,1] has a score less than 5. |
| 31 | +[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5. |
| 32 | +Thus, there are 5 subarrays having scores less than 5. |
| 33 | +</pre> |
| 34 | + |
| 35 | +#### Constraints: |
| 36 | +* <code>1 <= nums.length <= 10<sup>5</sup></code> |
| 37 | +* <code>1 <= nums[i] <= 10<sup>5</sup></code> |
| 38 | +* <code>1 <= k <= 10<sup>15</sup></code> |
| 39 | + |
| 40 | +## Solutions (Rust) |
| 41 | + |
| 42 | +### 1. Solution |
| 43 | +```Rust |
| 44 | +impl Solution { |
| 45 | + pub fn count_subarrays(nums: Vec<i32>, k: i64) -> i64 { |
| 46 | + let mut prefix_sum = vec![0; nums.len() + 1]; |
| 47 | + let mut ret = 0; |
| 48 | + |
| 49 | + for i in 0..nums.len() { |
| 50 | + prefix_sum[i + 1] = prefix_sum[i] + nums[i] as i64; |
| 51 | + } |
| 52 | + |
| 53 | + for i in 0..nums.len() { |
| 54 | + let mut lo = 0; |
| 55 | + let mut hi = i + 1; |
| 56 | + |
| 57 | + while lo < hi { |
| 58 | + let mid = (lo + hi) / 2; |
| 59 | + let score = (prefix_sum[i + 1] - prefix_sum[mid]) * (i + 1 - mid) as i64; |
| 60 | + |
| 61 | + if score < k { |
| 62 | + hi = mid; |
| 63 | + } else { |
| 64 | + lo = mid + 1; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + ret += (i + 1 - hi) as i64; |
| 69 | + } |
| 70 | + |
| 71 | + ret |
| 72 | + } |
| 73 | +} |
| 74 | +``` |
0 commit comments