Longest Subarray With Restricted Pair Sums Problem
Description
LeetCode Problem 4067.
You are given an integer array nums.
A subarray nums[l..r] is valid if there are no three distinct indices i, j, and k such that l <= i, j, k <= r and:
nums[i] + nums[j] == nums[k]
Return the maximum length of a valid subarray of nums.
Example 1:
Input: nums = [2,3,5,3,2,1]
Output: 3
Explanation:
Consider the subarray [3, 5, 3]. The pairs of elements at distinct indices have the following sums:
- 3 + 5 = 8
- 3 + 3 = 6, using the two different occurrences of 3
- 5 + 3 = 8
None of these sums is an element at the remaining index, so the subarray is valid.
Every subarray of length 4 contains 2, 3, and 5 at distinct indices, where 2 + 3 = 5. Therefore, no longer valid subarray exists, and the answer is 3.
Example 2:
Input: nums = [3,4,5,6]
Output: 4
Explanation:
The sums obtained from every pair of elements at distinct indices are 7, 8, 9, 9, 10, and 11. None of these values appears at the remaining index, so the entire array is valid.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 500
Solution
Approach: Sliding Window with Pair Counts
Validity is monotone: every subarray of a valid subarray is also valid, so a sliding window works.
Keep two count arrays over the pairs of elements currently inside the window (before adding the new right end):
cntS[v]: how many pairs have sumv;cntD[v]: how many pairs have absolute differencev.
When a new value x arrives at the right end, it breaks the window if x is the sum of two earlier elements (cntS[x] > 0), or if x is one of the two summands, meaning some earlier element equals another earlier element plus x (cntD[x] > 0). While that is the case, drop the left end: remove all pairs that contain it from both arrays. Then add all pairs formed by x and the elements in the window, and update the answer with the window length.
Every element is added and removed once, each time against at most n others, and the values are at most 500.
Complexity: O(n2) time and O(max value) extra space.
class Solution:
def maxSubarray(self, nums: List[int]) -> int:
mx = max(nums)
cnt_s = [0] * (mx << 1 | 1)
cnt_d = [0] * (mx + 1)
ans = l = 0
for r, x in enumerate(nums):
while cnt_s[x] > 0 or cnt_d[x] > 0:
y = nums[l]
l += 1
for z in nums[l:r]:
cnt_s[y + z] -= 1
cnt_d[abs(y - z)] -= 1
for y in nums[l:r]:
cnt_s[x + y] += 1
cnt_d[abs(x - y)] += 1
ans = max(ans, r - l + 1)
return ans