Prefix sum problem 1 GFG Query(1,8)
import java.util.Arrays;
public class PrefixSum {
// Prefix sum of an array
public static int[] prefixSum(int[] arr){
int n = arr.length;
int[] array = new int[n];
int sum = 0;
for(int i = 0; i < n; i++){
sum += arr[i];
array[i] = sum;
}
return array;
}
public static int getSum(int[] arr, int l, int r) {
int n = arr.length;
int[] array = new int[n];
int solution = arr[r];
array = prefixSum(arr);
if(l != 0){
solution = array[r] - array[l - 1];
}
else
solution = array[r];
return solution;
}
public static void main(String[] args) {
int[] array = {2,8,3,9,6,5,4};
// System.out.print(Arrays.toString(prefixSum(array)));
System.out.println(getSum(array, 0, 2));
}
}
Comments
Post a Comment