Longest Subarray Divisible by K with At Most One Negation I Problem
Description
LeetCode Problem 4063.
You are given an integer array nums and an integer k.
A subarray is valid if its sum is divisible by k, or can become divisible by k by negating one element within that subarray.
Negating an element means replacing its value x with -x.
Return the length of the longest valid subarray. If no valid subarray exists, return 0.
Example 1:
Input: nums = [4,1,2], k = 3
Output: 3
Explanation:
- The sum of the entire array is 7, and 7 % 3 = 1, so it is not divisible by k = 3.
- Negating nums[2] = 2 changes the sum to 4 + 1 − 2 = 3, which is divisible by k.
- Therefore, the entire array is a valid subarray, giving a length of 3.
Example 2:
Input: nums = [5,3,4], k = 7
Output: 2
Explanation:
- The sum of the entire array is 12, and negating any one of its elements does not make its sum divisible by 7.
- However, the subarray [3, 4] has a sum of 7, which is divisible by k = 7 without any negation.
- Therefore, the longest valid subarray has a length of 2.
Example 3:
Input: nums = [2,2,5], k = 6
Output: 2
Explanation:
- The sum of the entire array is 9, and negating any one of its elements does not make its sum divisible by 6.
- The subarray [2, 2] has a sum of 4. Negating either element changes it to [-2, 2] or [2, -2], both of which have a sum of 0.
- Therefore, the longest valid subarray has a length of 2.
Constraints:
1 <= nums.length <= 1000-10^5 <= nums[i] <= 10^51 <= k <= 10^5
Solution
Approach: Try Every Negation with Prefix Remainders
A subarray is valid if its sum is divisible by k, either as it is or after negating one element in it. Instead of choosing the subarray first, negate one element of the whole array and look for the longest subarray with sum divisible by k. A subarray that does not contain the negated element is still valid without any negation, so nothing invalid is counted, and every valid subarray is found when its negated element is the one we flip.
To find the longest subarray with sum divisible by k, scan the prefix sums modulo k and remember the first index of each remainder (the remainder 0 first appears at index -1). When a remainder appears again at index i, the subarray between the two positions has sum divisible by k, and its length is i minus the first index.
Run this for the original array and for each of the n negations.
Complexity: O(n2) time and O(n) extra space.
class Solution:
def longestSubarray(self, nums: List[int], k: int) -> int:
def f(nums: List[int], k: int) -> int:
d = {0: -1}
s = res = 0
for i, x in enumerate(nums):
s = (s + x) % k
if s in d:
res = max(res, i - d[s])
else:
d[s] = i
return res
ans = f(nums, k)
for i, x in enumerate(nums):
nums[i] = -x
ans = max(ans, f(nums, k))
nums[i] = x
return ans