#K78147. Contiguous Subarray Sum
Contiguous Subarray Sum
Contiguous Subarray Sum
You are given an array of n integers and an integer k. Your task is to determine the number of contiguous subarrays that sum to exactly k.
A contiguous subarray is a sequence of elements from the array that occupy consecutive positions. Formally, for an array \(a\) of length \(n\), you need to count the number of pairs \((l, r)\) (with \(1 \leq l \leq r \leq n\)) such that:
\[ \sum_{i=l}^{r} a_i = k \]Try to solve this problem efficiently.
inputFormat
The input is given via standard input (stdin) and has the following format:
- The first line contains two integers
n
andk
, wheren
is the number of elements in the array andk
is the target sum. - The second line contains
n
space-separated integers representing the elements of the array.
outputFormat
Output a single integer on a new line: the number of contiguous subarrays whose elements sum to k
.
5 7
3 4 7 2 -3
2