Count Subarrays That Add Up to k
Problem statement
Given an integer array nums (values may be negative or zero) and an integer k, count the subarrays whose values add up to exactly k.
A subarray is a non-empty run of neighbouring elements. Two subarrays count separately when they start or end at different positions, even if they hold the same values.
Function
countSubarraysWithSum(nums: int[], k: int) → intExamples
Example 1
nums = [2,-1,3,-2,1]k = 2return = 4Four subarrays add up to 2: [2], [-1, 3], [2, -1, 3, -2] and [3, -2, 1].
Example 2
nums = [0,0,5]k = 0return = 3The subarrays [0] (first), [0] (second) and [0, 0] add up to 0. Each counts separately because it covers different positions.
Example 3
nums = [4,4]k = 5return = 0The possible sums are 4, 4 and 8. None of them is 5, so the answer is 0.
Constraints
1 <= nums.length <= 3000-1000 <= nums[i] <= 1000-3 * 10^6 <= k <= 3 * 10^6