Subarray Sum and Count
Given an array of N integers, find the number of subarrays whose sum is exactly equal to K. A subarray is a contiguous part of the array.
For example, if the array is [1, 2, 3] and K = 3, the subarrays are [1, 2] (sum 3) and [3] (sum 3). The answer is 2.
Input
The first line contains two integers N and K, separated by a space. The second line contains N integers, the elements of the array.
Elements of the array can be positive, negative, or zero.
Output
Print a single integer: the count of subarrays whose sum is exactly K.
Constraints
1 <= N <= 200000 -10^9 <= K <= 10^9 -10^9 <= A[i] <= 10^9 for each element A[i] in the array.
Example 1
4 3 1 2 1 1
2
Subarrays are [1, 2] (sum 3), [2, 1] (sum 3), [1, 1, 1] (sum 3). Count is 3.
Example 2
5 0 1 -1 1 -1 0
7
Subarrays are [1, -1] (sum 0), [-1, 1] (sum 0), [1, -1] (sum 0), [-1, 0] (sum -1, ignore), [0] (sum 0), [1, -1, 1, -1] (sum 0), [-1, 1, -1, 0] (sum -1, ignore), [1, -1, 0] (sum 0). Count is 5.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
4 3 1 2 1 1
5 0 1 -1 1 -1 0