From 031e3de7122b61023dfbcfbdd5d6ea470b0ab776 Mon Sep 17 00:00:00 2001 From: Shashi <47141879+kt-shashi@users.noreply.github.com> Date: Sat, 24 Dec 2022 10:13:12 +0530 Subject: [PATCH] Create PrefixSum.cpp --- PrefixSum.cpp | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 PrefixSum.cpp diff --git a/PrefixSum.cpp b/PrefixSum.cpp new file mode 100644 index 0000000..78c2e0b --- /dev/null +++ b/PrefixSum.cpp @@ -0,0 +1,51 @@ +/* + +Given an array of N integers +Given Q queries +In each query given a range, L and R +Print the sum of array elements from L to R (inclusive) + +Constratints: +1 <= N <= 10^5 +1 <= a[i] <= 10^9 +1 <= Q <= 10^5 +1 <= L , R <= N + +*/ + +#include +using namespace std; + +const int N = 1e5 + 10; +int a[N]; +int prefixSum[N]; + +int main() +{ + + int n; + cin >> n; + + // NOTE: Take input from 1 in prefix sum + for (int i = 1; i <= n; i++) + cin >> a[i]; + + // Pre computing + for (int i = 1; i <= n; i++) + prefixSum[i] = prefixSum[i - 1] + a[i]; + + int q; + cin >> q; + + while (q--) + { + + int l, r; + cin >> l >> r; + + cout << prefixSum[r] - prefixSum[l - 1] << endl; + } + + // Time complexity: + // O(N) + O(Q) = O(10^5) +}