#K63382. Count Subarrays with Given Sum
Count Subarrays with Given Sum
Count Subarrays with Given Sum
You are given an array of positive integers and a target sum T. Your task is to compute the number of contiguous subarrays (subarrays) whose elements sum exactly to T.
More formally, given an array \(a_1, a_2, \dots, a_n\) and an integer target \(T\), find the number of pairs \((i, j)\) with \(1 \le i \le j \le n\) such that
[ \sum_{k=i}^{j} a_k = T ]
Your solution should run in O(n) time on average using an efficient algorithm based on prefix sums and hashing.
inputFormat
The input is provided via standard input (stdin) and has two lines:
- The first line contains two integers separated by a space:
n
(the number of elements in the array) andT
(the target sum). - The second line contains
n
positive integers separated by spaces representing the elements of the array.
outputFormat
Output to standard output (stdout) a single integer: the number of contiguous subarrays that sum exactly to T
.## sample
5 6
1 2 3 4 2
2