I am trying to create a continuous subArray from a given array which is equal to the given sum and return the first and last index as an ArrayList. This is the solution i could think of which actually passed 52 testcases but failed for a really large set of Arrays where it is returning -1 instead.
Input - arr = {1,2,3,7,5} n = 5 s = 12Expected output = 2, 4
static ArrayList<Integer> subarraySum(int[] arr, int n, int s) {
ArrayList<Integer> result = new ArrayList<>();
result.add(0, -1);
for (int i = 0; i < n; i++) {
int sum = arr[i];
for (int j = i+1; j < n; j++) {
sum += arr[j];
if (sum == s) {
result.add(1, j+1);
result.set(0, i+1);
return result;
}
}
}
return result;
}