Skip to content

Commit dc598f8

Browse files
Range Sum Problem Solved Using Prefix Sum
1 parent e971e02 commit dc598f8

5 files changed

+43
-1
lines changed

input.txt

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
4 3
2+
5 5 2 3
3+
1 3
4+
2 3
5+
1 4

output.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
12
2+
7
3+
15

range_sum_query.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int main()
5+
{
6+
long long int n, q;
7+
cin >> n >> q;
8+
long long int a[n];
9+
long long int pre[n] = {0};
10+
for (long long int i = 0; i < n; i++)
11+
{
12+
cin >> a[i];
13+
if (i != 0)
14+
pre[i] = a[i] + pre[i - 1];
15+
else
16+
pre[i] = a[i];
17+
}
18+
19+
while (q--)
20+
{
21+
long long int l, r;
22+
cin >> l >> r;
23+
l--;
24+
r--;
25+
long long int sum = 0;
26+
l == 0 ? sum = pre[r] : sum = pre[r] - pre[l - 1];
27+
cout << sum << endl;
28+
}
29+
30+
return 0;
31+
}

range_sum_query.exe

51 KB
Binary file not shown.

tempCodeRunnerFile.cpp

+4-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
1-
int
1+
ong int i = 0; i < n; i++)
2+
// {
3+
// cout << pre[i] << endl;
4+
// }

0 commit comments

Comments
 (0)