Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum. The second line of each test case contains N space separated integers denoting the array elements.
Output:
For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1010
Example:
Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output:
2 4
1 5
Explanation :
Testcase1: sum of elements from 2nd position to 4th position is 12
Testcase2: sum of elements from 1st position to 5th position is 15
/*package whatever //do not write package name here */
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
//code
Scanner s = new Scanner(System.in);
int testNum = s.nextInt(); //testcaseNum
for (int i = 0; i < testNum; i++) {
int n = s.nextInt(); //arr.length
int sum = s.nextInt(); //arr.sum
int[] arr = new int[n];
for(int j = 0; j < n; j++) {
arr[j] = s.nextInt();
}
subArraySum(arr,n,sum);
}
}
static void subArraySum(int[] arr, int n, int sum) {
int curr_sum, i , j;
//pick a starting point
for(i = 0; i < n; i++) {
curr_sum = arr[i];
//try all subarrays starting with 'i'
for(j = i + 1; j <= n; j++) {
if(curr_sum == sum) {
int p = j - 1; //sum found between indexes i ~ p
System.out.println("sum of elements from " + i +"nd position to " + p +"th position is " + curr_sum);
}
if(curr_sum > sum || j==n) break;
curr_sum = curr_sum + arr[j];
}
}
}
}
For Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Your Output is:
sum of elements from 1nd position to 3th position is 12
sum of elements from 3nd position to 4th position is 12
sum of elements from 0nd position to 4th position is 15
sum of elements from 3nd position to 5th position is 15
sum of elements from 6nd position to 7th position is 15