Java Program for Range sum queries without updates
Last Updated :
12 Jun, 2022
Given an array arr of integers of size n. We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples:
Input : arr[] = {1, 2, 3, 4, 5}
i = 1, j = 3
i = 2, j = 4
Output : 9
12
Input : arr[] = {1, 2, 3, 4, 5}
i = 0, j = 4
i = 1, j = 2
Output : 15
5
Java
import java.util.*;
import java.lang.*;
class GFG {
public static void preCompute( int arr[], int n, int pre[])
{
pre[ 0 ] = arr[ 0 ];
for ( int i = 1 ; i < n; i++)
pre[i] = arr[i] + pre[i - 1 ];
}
public static int rangeSum( int i, int j, int pre[])
{
if (i == 0 )
return pre[j];
return pre[j] - pre[i - 1 ];
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 5 };
int n = arr.length;
int pre[] = new int [n];
preCompute(arr, n, pre);
System.out.println(rangeSum( 1 , 3 , pre));
System.out.println(rangeSum( 2 , 4 , pre));
}
}
|
Time Complexity: O(n), where n represents the size of the given array.
Auxiliary Space: O(n), where n represents the size of the given array.
Please refer complete article on Range sum queries without updates for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...