Count Subarrays Sum K
Python
Hard
3 views
Problem Description
Read n integers and target K. Count number of subarrays with sum exactly K. Output the count.
Input Format
First line n K. Second line n integers.
Output Format
One integer count.
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
n=int(p[0]); K=int(p[1])
a=list(map(int,p[2:2+n]))
mp={0:1}
sm=0
ans=0
for x in a:
sm+=x
ans+=mp.get(sm-K,0)
mp[sm]=mp.get(sm,0)+1
sys.stdout.write(str(ans))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!