prefixSum
to 0 and longestSubarray
to 0.indices
with the key-value pair {0: -1}
to handle the case when a subarray starting from index 0 sums to k
.nums
using an index i
.
a. Add nums[i]
to prefixSum
.
b. If prefixSum == k
, update longestSubarray
to i + 1
.
c. If prefixSum - k
is in indices
, update longestSubarray
to the maximum of its current value and i - indices[prefixSum - k]
.
d. If prefixSum
is not in indices
, add prefixSum
to indices
with the value i
.longestSubarray
.