← DiffPush

Number of subarray sum equal k

Standard Bar Arrays · Medium O(n) · O(n)

Counting Settled Batches in a Netted Ledger

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.

Constraints

Examples

Example 1

Input: {"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.

Example 2

Input: {"nums":[1,2,3],"k":3}
Output: 2
The run 1,2 and the single batch 3 both net to 3.

Solve this in your browser →

Also on LeetCode ↗