C++ Program for Range sum queries without updates?

Server Side ProgrammingProgrammingC++

Here we will see how to get the sum of elements from index i to index j in an array. This is basically the range query. The task is easy by just running one loop from index i to j, and calculate the sum. But we have to care about that this kind of range query will be executed multiple times. So if we use the mentioned method, it will take much time. To solve this problem using more efficient way we can get the cumulative sum at first, then the range sum can be found in constant time. Let us see the algorithm to get the idea.

Algorithm

rangeSum(arr, i, j)

begin
   c_arr := cumulative sum of arr
   if i = 0, then
      return c_arr[j];
      return c_arr[j] – c_arr[i-1]
end

Example

 Live Demo

#include<iostream>
using namespace std;
void cumulativeSum(int c_arr[], int arr[], int n){
   c_arr[0] = arr[0];
   for(int i = 1; i<n; i++){
      c_arr[i] = arr[i] + c_arr[i-1];
   }
}
int rangeSum(int c_arr[], int i, int j){
   if( i == 0){
      return c_arr[j];
   }
   return c_arr[j] - c_arr[i-1];
}
main() {
   int data[] = {5, 4, 32, 8, 74, 14, 23, 65};
   int n = sizeof(data)/sizeof(data[0]);
   int c_arr[n];
   cumulativeSum(c_arr, data, n); //get cumulative sum
   cout << "Range sum from index (2 to 5): " << rangeSum(c_arr, 2, 5) << endl;
   cout << "Range sum from index (0 to 3): " << rangeSum(c_arr, 0, 3) << endl;
   cout << "Range sum from index (4 to 7): " << rangeSum(c_arr, 4, 7) << endl;
}

Output

Range sum from index (2 to 5): 128
Range sum from index (0 to 3): 49
Range sum from index (4 to 7): 176
raja
Published on 26-Jul-2019 07:22:12
Advertisements