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 ofnumswhose score is strictly less thank.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [2,1,4,3,5], k = 10
Output: 6
Explanation:
The 6 subarrays having scores less than 10 are:
- [2] with score 2 * 1 = 2.
- [1] with score 1 * 1 = 1.
- [4] with score 4 * 1 = 4.
- [3] with score 3 * 1 = 3.
- [5] with score 5 * 1 = 5.
- [2,1] with score (2 + 1) * 2 = 6.
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.
Example 2:
Input: nums = [1,1,1], k = 5
Output: 5
Explanation:
Every subarray except [1,1,1] has a score less than 5.
[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.
Thus, there are 5 subarrays having scores less than 5.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k <= 1015
Solutions
Solution 1: Prefix Sum + Binary Search
Thinking
A subarray’s score is its sum times its length. Enumerating all subarrays is \(O(n^2)\) and fails for \(n \le 10^5\). All values are positive, so for a fixed right end a longer window has a larger score, and valid left ends form a prefix.
Prefix sums answer any range sum in constant time. Binary-search the largest length \(l\) with \((s[i]-s[i-l])\times l < k\). That right end contributes \(l\) subarrays.
First, we calculate the prefix sum array \(s\) of the array \(\textit{nums}\), where \(s[i]\) represents the sum of the first \(i\) elements of \(\textit{nums}\).
Next, we enumerate each element of \(\textit{nums}\) as the last element of a subarray. For each element, we can use binary search to find the maximum length \(l\) such that \(s[i] - s[i - l] \times l < k\). The number of subarrays ending at this element is \(l\), and summing up all \(l\) gives the final answer.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\).
Method 1 stores a prefix array and pays a logarithmic cost per right end. Positivity makes the score decrease as the left end moves right, so the left pointer only advances. Maintain the window sum and count valid subarrays in one linear scan.
We can use the two-pointer technique to maintain a sliding window such that the sum of elements in the window is less than \(k\). The number of subarrays ending at the current element is equal to the length of the window. Summing up all the window lengths gives the final answer.
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\). The space complexity is \(O(1)\).