Problem
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 thenumber of non-empty subarrays of nums
whose score isstrictly less than k
.
A subarray is a contiguous sequence of elements within an array.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
1 <= k <= 10^15
Solution
Method 1 - Using Sliding Window
To solve this problem, we need to find the number of non-empty subarrays whose score (product of sum and length) is strictly less than k
. Here’s the detailed explanation:
Approach
- Sliding Window Technique:
- We use the sliding window method to efficiently compute the sum and length of subarrays in linear time. This avoids computing the score for all possible subarrays, which would take
O(n^2)
time.
- We use the sliding window method to efficiently compute the sum and length of subarrays in linear time. This avoids computing the score for all possible subarrays, which would take
- Two Pointers:
- Maintain two pointers (
l
andr
) to track the current subarray. - Expand the window (
r
) to include more elements and add them to the cumulative sum. - If the score (
current sum * (r - l + 1)
) exceedsk
, incrementl
(contracting the window) until the score becomes less thank
.
- Maintain two pointers (
- Count Valid Subarrays:
- For every
r
, the number of valid subarrays ending atr
is(r - l + 1)
because all subarrays starting froml
tor
satisfy the condition.
- For every
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. The left pointer moves at most once for every right pointer. Thus, sliding window approach ensuresO(n)
time complexity. - 🧺 Space complexity:
O(1)
as no additional space is used beyond variables for the algorithm.