Range Sum Query - Immutables in C++

C++Server Side ProgrammingProgramming

<p>Suppose we have an array of integers. We have to find the sum of the elements present from index i to j. Two things we have to keep in mind that the array will be immutable, so elements will not be altered, and there will be multiple such queries. So we have to care about the execution time for a large number of queries. Suppose the array is like A = [5, 8, 3, 6, 1, 2, 5], then if query is (A, 0, 3), then it will be 5 + 8 + 3 + 6 = 22.</p><p>To solve this, we will follow these steps &minus;</p><ul class="list"><li>Take one array B. B[i] will store the sum of elements from 0 to i</li><li>for query perform B[j] &ndash; B[i &ndash; 1]</li></ul><p>Let us see the following implementation to get a better understanding &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/ZUkdX2W3" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;bits/stdc++.h&gt; using namespace std; class NumArray { &nbsp; &nbsp;public: &nbsp; &nbsp;vector &lt;int&gt; pre; &nbsp; &nbsp;NumArray(vector&lt;int&gt;&amp; nums) { &nbsp; &nbsp; &nbsp; pre.clear(); &nbsp; &nbsp; &nbsp; int n = nums.size(); &nbsp; &nbsp; &nbsp; pre.resize(n); &nbsp; &nbsp; &nbsp; for(int i = 0; i &lt; n; i++){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(i == 0)pre[0] = nums[0]; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;pre[i] = pre[i - 1] + nums[i]; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;int sumRange(int i, int j) { &nbsp; &nbsp; &nbsp; if(i == 0)return pre[j]; &nbsp; &nbsp; &nbsp; return pre[j] - pre[i - 1]; &nbsp; &nbsp;} }; main(){ &nbsp; &nbsp;vector&lt;int&gt; v = {5,8,3,6,1,2,5}; &nbsp; &nbsp;NumArray na(v); &nbsp; &nbsp;cout&lt;&lt;na.sumRange(0,2)&lt;&lt;endl; &nbsp; &nbsp;cout&lt;&lt;na.sumRange(2,5)&lt;&lt;endl; &nbsp; &nbsp;cout&lt;&lt;na.sumRange(0,5)&lt;&lt;endl; }</pre><h2>Input</h2><pre class="result notranslate">Initialize it with [5,8,3,6,1,2,5] Call sumRange(0,2) sumRange(2,5) sumRange(0,5)</pre><h2>Output</h2><pre class="result notranslate">16 12 25</pre>
raja
Updated on 28-Apr-2020 10:50:14

Advertisements