Standard Bar Arrays · Medium O(n) · O(n)
A payments engine records the net amount of each processing batch in order, and batches may be negative when refunds outnumber charges. A reconciliation pass must count how many contiguous runs of batches net out to an exact settlement amount. The runs may overlap and may be of any length.
Input: An array nums of n integers and an integer k, the target net amount.
Output: The number of contiguous subarrays of nums whose elements sum to exactly k.
1 <= n <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7Input: {"nums":[1,1,1],"k":2}
Output: 2
The pairs of adjacent batches net to 2, and no longer run does, so the count is 2.
Input: {"nums":[1,2,3],"k":3}
Output: 2
The run 1,2 and the single batch 3 both net to 3.