File tree Expand file tree Collapse file tree
Problems/Mathematics/Day-01/sol/RonakGoyal Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+ using namespace std ;
3+
4+ /*
5+ Problem Statement:
6+ Given an array of integers and multiple range queries, find the sum
7+ of elements in a given range for each query.
8+
9+ Approach (Using Prefix Sums):
10+ We construct a prefix sum array where prefix[i] stores the sum of
11+ elements from index 0 to i. For any range [l, r], the sum can be
12+ calculated in O(1) time using:
13+ prefix[r] - prefix[l - 1].
14+
15+ Time Complexity:
16+ O(n + q)
17+
18+ Space Complexity:
19+ O(n)
20+
21+ Example:
22+ Input:
23+ 5
24+ 1 2 3 4 5
25+ 1
26+ 1 3
27+
28+ Output:
29+ 9
30+
31+ */
32+
33+ int main () {
34+ int n;
35+ cin >> n;
36+
37+ vector<int > arr (n), prefix (n);
38+
39+ // Building prefix sum array
40+ for (int i = 0 ; i < n; i++) {
41+ cin >> arr[i];
42+ if (i == 0 ) {
43+ prefix[i] = arr[i];
44+ } else {
45+ prefix[i] = prefix[i - 1 ] + arr[i];
46+ }
47+ }
48+
49+ int q;
50+ cin >> q;
51+
52+ // Answering queries
53+ while (q--) {
54+ int l, r;
55+ cin >> l >> r;
56+
57+ int sum;
58+ if (l == 0 ) {
59+ sum = prefix[r];
60+ } else {
61+ sum = prefix[r] - prefix[l - 1 ];
62+ }
63+
64+ cout << sum << endl;
65+ }
66+
67+ return 0 ;
68+ }
You can’t perform that action at this time.
0 commit comments