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.
A subarray is a contiguous, non-empty sequence of elements within an array.
Example 1:
Input: nums = [4,1,2], k = 3
Output: 3
Explanation:
7 % 3 = 1, so it is not divisible by k = 3.nums[2] = 2 changes the sum to 4 + 1 − 2 = 3, which is divisible by k.Example 2:
Input: nums = [5,3,4], k = 7
Output: 2
Explanation:
[3, 4] has a sum of 7, which is divisible by k = 7 without any negation.Example 3:
Input: nums = [2,2,5], k = 6
Output: 2
Explanation:
[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.Constraints:
1 <= nums.length <= 105-105 <= nums[i] <= 1051 <= k <= 3000Loading editor...
[4,1,2] 3