Prefix Sum Queries
Python
Medium
2 views
Problem Description
Read n integers and q queries l r (1-based). Output sum of each range.
Input Format
First line n q. Second line n integers. Next q lines l r.
Output Format
q lines sums.
Sample Test Case
Input:
5 3
1 2 3 4 5
1 3
2 4
4 5
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p: sys.exit(0)
it=iter(p)
n=int(next(it)); q=int(next(it))
a=[0]*(n+1)
for i in range(1,n+1):
a[i]=int(next(it))
pref=[0]*(n+1)
for i in range(1,n+1):
pref[i]=pref[i-1]+a[i]
out=[]
for _ in range(q):
l=int(next(it)); r=int(next(it))
out.append(str(pref[r]-pref[l-1]))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!