You are given an integer array nums and two integers goal and k.
A subarraynums[i..j] is considered distant if the absolute difference between its sum and goal is at leastk.
Return the number of distant subarrays.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input:nums = [1,2,1], goal = 4, k = 1
Output:5
Explanation:
The distant subarrays for k = 1 are:
i
j
nums[i..j]
Sum
abs(sum - goal)
0
0
[1]
1
3
1
1
[2]
2
2
2
2
[1]
1
3
0
1
[1, 2]
3
1
1
2
[2, 1]
3
1
Thus, the answer is 5.
Example 2:
Input:nums = [2,-1,3], goal = 2, k = 2
Output:2
Explanation:
The distant subarrays for k = 2 are:
i
j
nums[i..j]
Sum
abs(sum - goal)
1
1
[-1]
-1
3
0
2
[2, -1, 3]
4
2
Thus, the answer is 2.
Example 3:
Input:nums = [-3,1,2], goal = 0, k = 3
Output:2
Explanation:
The distant subarrays for k = 3 are:
i
j
nums[i..j]
Sum
abs(sum - goal)
0
0
[-3]
-3
3
1
2
[1, 2]
3
3
Thus, the answer is 2.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
-109 <= goal <= 109
0 <= k <= 109
Solutions
Solution 1: Prefix Sum + Binary Indexed Tree
Thinking
There are quadratically many subarrays, so \(n = 10^5\) rules out enumeration. The complement of \(|sum - \textit{goal}| \ge k\) is \(|sum - \textit{goal}| < k\); subtracting that count from the total is cleaner.
Prefix sums turn a subarray sum into a difference of two points. For each right endpoint we need how many earlier prefix sums fall inside a numeric interval.
After sorting the prefix sums we binary-search the Fenwick indices, query the interval, then insert the current value.
Let \(s\) be the prefix-sum array of \(\textit{nums}\) (\(s[0] = 0\)). The sum of the subarray \(\textit{nums}[L..R-1]\) is \(s[R] - s[L]\), and it is distant if and only if \(|s[R] - s[L] - \textit{goal}| \ge k\).
There are \(\frac{n(n+1)}{2}\) nonempty subarrays. We count those that fail the condition, i.e. \(|s[R] - s[L] - \textit{goal}| < k\), and subtract that count from the total.
The inequality is equivalent to
\[ s[R] - \textit{goal} - k < s[L] < s[R] - \textit{goal} + k \]
that is, \(s[L]\) lies in the closed interval \([s[R] - \textit{goal} - k + 1,\, s[R] - \textit{goal} + k - 1]\).
Enumerate the prefix sums \(v = s[R]\) from left to right. Among the prefix sums already inserted, query how many fall in \([a, b]\) and subtract that from the answer, then insert \(v\). For discretization we sort \(s\) and locate Binary Indexed Tree indices by binary search.
The time complexity is \(O(n \times \log n)\) and the space complexity is \(O(n)\), where \(n\) is the length of \(\textit{nums}\).