Given an integer array nums and an integer k, return the maximum length of a subarray that sums tok. If there is not one, return 0 instead.
Example 1:
Input: nums = [1,-1,5,-2,3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
Example 2:
Input: nums = [-2,-1,2,1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.
Constraints:
1 <= nums.length <= 2 * 105
-104 <= nums[i] <= 104
-109 <= k <= 109
Solutions
Solution 1: Hash Table + Prefix Sum
We can use a hash table \(\textit{d}\) to record the first occurrence index of each prefix sum in the array \(\textit{nums}\), initializing \(\textit{d}[0] = -1\). Additionally, we define a variable \(\textit{s}\) to keep track of the current prefix sum.
Next, we iterate through the array \(\textit{nums}\). For the current number \(\textit{nums}[i]\), we update the prefix sum \(\textit{s} = \textit{s} + \textit{nums}[i]\). If \(\textit{s} - k\) exists in the hash table \(\textit{d}\), let \(\textit{j} = \textit{d}[\textit{s} - k]\), then the length of the subarray that ends at \(\textit{nums}[i]\) and satisfies the condition is \(i - j\). We use a variable \(\textit{ans}\) to maintain the length of the longest subarray that satisfies the condition. After that, if \(\textit{s}\) does not exist in the hash table, we record \(\textit{s}\) and its corresponding index \(i\) by setting \(\textit{d}[\textit{s}] = i\). Otherwise, we do not update \(\textit{d}[\textit{s}]\). It is important to note that there may be multiple positions \(i\) with the same value of \(\textit{s}\), so we only record the smallest \(i\) to ensure the subarray length is the longest.
After the iteration ends, we return \(\textit{ans}\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\).