MV_81 MV_81 - 1 month ago 7
Java Question

Find arrray intervals that add up to a given value

I need to create a method that finds intervals within an array that add up to 13

example:
{10,0,3,0,1,1,1,10,5,5,5}

0 and 2 add to 13

0 and 3 add to 13

3 and 7 add to 13

4 and 7 add to 13

EDIT: this is the output I'm getting

interval 0 and 2 is 13

interval 0 and 6 is 13

interval 2 and 9 is 13

This is what I tried:

public static void findSum (int[] arr) {
int i = 0;
int j = 1;
int resu = 0;

while (i < arr.length-1) {
if (resu == 13) {
j++;
}
resu = arr[i] + arr[j];
while (j < arr.length-1 && resu < 13){
j++;
resu = resu + arr[j];
}
if (resu == 13){
System.out.println("interval " + i + " and " + j + " is 13");
}
if (resu != 13){
i++;
}
}
}

Answer

I think you had some issues with declaring variables in wrong places as well as unnecessary conditional statements. This should do it for you..

public static void findSum (int[] arr) {
    int i = 0;


    while (i < arr.length-1) {
        //define resu and j on the inside as these change with every i
        //start j from the i+1
        int j = i+1;
        //define resu as the ith element
        int resu = arr[i];
        //keep adding to resu until we have reached end of array or until resu is greater than the target  
        while (j < arr.length-1 && resu < 14){
            //add the jth element of the array
            resu = resu + arr[j]; 
            //print if we have a match
            if (resu == 13){    
                System.out.println("interval " + i + " and " + j + " is 13");

            }
            j++;
        }
            i++;
    }
}
Comments