Continuous subarray with given sum

106 Views Asked by At

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;
}
1

There are 1 best solutions below

0
Johann Schwarze On

The following code should work:

static ArrayList<Integer> subarraySum(int[] arr, int s) {
    ArrayList<Integer> result = new ArrayList<>();
    
    for (int i = 0; i < arr.length; i++) {
        int sum = 0;
        for (int j = i; j < arr.length; j++) {
            sum += arr[j];
            
            if (s == sum) {
                result.add(i+1);
                result.add(j+1);
                return result;
            }
        }
    }
    
    result.add(-1);
    return result;
}