0

What I'm trying to do is; I have given a sorted array such as; 1,1,1,2,2,3. Then I'm given a number such as; 6. Then I'm trying to find minimum number of array elements that I have to sum to find this number. I start from the end of the array to sum elements. The answer should be 3 because I used 3 items in the array to sum just like;

3+2+2 (starting from the end) >= 6.

If all the sums still not greater then the given number, I return (-1) to indicate that I can never reach the given number.

My Recursive function is as follows but I'm getting "Missing Return Statement" error. How can I solve thi problem for the given question.

    public static int findIt(int[] arr, int index, int min)
{
    if(index >=0)
    {
        int calc=0;
        int counter=0;
        for(int from = arr.length-1 ; from>=index; from--)
        {
            calc += arr[from];
            counter++;
        }
        if(calc>=min)
            return counter;
        else
            findIt(arr, --index, min);
    }
   else
    return -1;
}
1
  • What happens after else findIt(arr, --index, min);? Commented Feb 22, 2015 at 14:36

3 Answers 3

2

Instead of:

findIt(arr, --index, min);

Return the value from it like:

return findIt(arr, --index, min);
Sign up to request clarification or add additional context in comments.

Comments

0

The missing return should be after the line findIt(arr, --index, min);

Comments

0

You're missing a return:

public static int findIt(int[] arr, int index, int min)
{
    if(index >=0)
    {
        int calc=0;
        int counter=0;
        for(int from = arr.length-1 ; from>=index; from--)
        {
            calc += arr[from];
            counter++;
        }
        if(calc>=min)
            return counter;
        else
            findIt(arr, --index, min); // <=== Here
    }
   else
    return -1;
}

Putting a return in front of findIt(arr, --index, min); will return the result of findIt.

If a function declares that it returns a value, all paths through the code must do so. And separately, for this function to work correctly, you really want to return the result of that recursive findIt call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.