Total Continuous Subarray Sum Equals K
Given a list of integers nums and an integer k, return the total number of continuous subarrays whose elements sum to exactly k.
Method Signature
int subarraySum(List<Integer> nums, int k)
nums contains the integers in their original order.
k is the required sum of a subarray.
- Return the number of continuous subarrays having a sum equal to
k.
Subarray Rules
- A subarray must contain one or more consecutive elements.
- Different start or end indices represent different subarrays.
- The list may contain positive numbers, negative numbers, and zeroes.
Constraints
1 ≤ nums.size() ≤ 20,000
-1,000 ≤ nums.get(i) ≤ 1,000
-10,000,000 ≤ k ≤ 10,000,000
Examples
Example 1
subarraySum(nums = [2, -1, 2, 1], k = 3)
Output: 2
The continuous subarrays [2, -1, 2] and [2, 1] each have a sum of 3.
Example 2
subarraySum(nums = [0, 0, 0], k = 0)
Output: 6
All six possible non-empty continuous subarrays have a sum of 0.
Example 3
subarraySum(nums = [4, -2, -2, 5], k = 4)
Output: 1
The only continuous subarray whose sum equals 4 is [4].