Problem Statement: Given an array of integers, answer queries of the form: [i, j] : Print the sum of array elements from A[i] to A[j], both inclusive
This is the code I used:
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc=new Scanner(System.in); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); int n=sc.nextInt(); long arr[]=new long[n]; for(int i=0;i<n;i++) arr[i]=sc.nextLong(); long farr[]=new long[n]; farr[0]=arr[0]; for(int i=1;i<n;i++) farr[i]=farr[i-1]+arr[i]; int q=sc.nextInt(); while(q-->0){ int i=sc.nextInt(); int j=sc.nextInt(); if(i!=0){ //I'm converting long value to String bcoz bw can't write long value in buffer String s=String.valueOf(farr[j]-farr[i-1]); bw.write(s); } else{ String s=String.valueOf(farr[j]); bw.write(s); } } bw.flush(); bw.close(); } } I tried the above code for Sum of Subarray problem