Editorial for Subarray Sums II
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let be the prefix sum of the first
elements, with
.
The sum of the subarray from
to
is
.
So when we are at a prefix sum , we need to know how many earlier prefix sums equal
. Every such earlier prefix sum gives one subarray ending at
whose sum is
.
We scan the array from left to right, maintain the current prefix sum, and store how many times each prefix sum has appeared in a dictionary.
This is time.
Solution (Python)
import sys
data = list(map(int, sys.stdin.buffer.read().split()))
n, x = data[0], data[1]
values = data[2 : 2 + n]
seen = {0: 1}
prefix = 0
answer = 0
for value in values:
prefix += value
answer += seen.get(prefix - x, 0)
seen[prefix] = seen.get(prefix, 0) + 1
print(answer)
Comments