C++ Program for Range sum queries without updates?

Server Side ProgrammingProgrammingC++

<p>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.</p><h2>Algorithm</h2><h4>rangeSum(arr, i, j)</h4><pre class="result notranslate">begin &nbsp; &nbsp;c_arr := cumulative sum of arr &nbsp; &nbsp;if i = 0, then &nbsp; &nbsp; &nbsp; return c_arr[j]; &nbsp; &nbsp; &nbsp; return c_arr[j] &ndash; c_arr[i-1] end</pre><h2>Example</h2><p><a class="demo" href="http://tpcg.io/lYLBfP" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include&lt;iostream&gt; using namespace std; void cumulativeSum(int c_arr[], int arr[], int n){ &nbsp; &nbsp;c_arr[0] = arr[0]; &nbsp; &nbsp;for(int i = 1; i&lt;n; i++){ &nbsp; &nbsp; &nbsp; c_arr[i] = arr[i] + c_arr[i-1]; &nbsp; &nbsp;} } int rangeSum(int c_arr[], int i, int j){ &nbsp; &nbsp;if( i == 0){ &nbsp; &nbsp; &nbsp; return c_arr[j]; &nbsp; &nbsp;} &nbsp; &nbsp;return c_arr[j] - c_arr[i-1]; } main() { &nbsp; &nbsp;int data[] = {5, 4, 32, 8, 74, 14, 23, 65}; &nbsp; &nbsp;int n = sizeof(data)/sizeof(data[0]); &nbsp; &nbsp;int c_arr[n]; &nbsp; &nbsp;cumulativeSum(c_arr, data, n); //get cumulative sum &nbsp; &nbsp;cout &lt;&lt; &quot;Range sum from index (2 to 5): &quot; &lt;&lt; rangeSum(c_arr, 2, 5) &lt;&lt; endl; &nbsp; &nbsp;cout &lt;&lt; &quot;Range sum from index (0 to 3): &quot; &lt;&lt; rangeSum(c_arr, 0, 3) &lt;&lt; endl; &nbsp; &nbsp;cout &lt;&lt; &quot;Range sum from index (4 to 7): &quot; &lt;&lt; rangeSum(c_arr, 4, 7) &lt;&lt; endl; }</pre><h2>Output</h2><pre class="result notranslate">Range sum from index (2 to 5): 128 Range sum from index (0 to 3): 49 Range sum from index (4 to 7): 176</pre>
Updated on 30-Jul-2019 22:30:26