0

I don't have much on this... my assignment is to create a recursion method that will output the highest value in an ArrayList of integers.

public static int maxValue(ArrayList<Integer> a)
    {
        if (a.isEmpty()) throw new NoSuchElementException ("Can't compute max of empty list.");
        if(a.size()==1){return a.get(0);}
        else {
            //not sure what to add here for the recursion
        }
    }

3 Answers 3

1

A way to do this is actually compare the first two values and remove the smallest one ( or one of them if equal) and set a base case of list size 1 like this:

public static int maxValue(ArrayList<Integer> a)
    {
        if (a.isEmpty()) return -1;
        if (a.size() == 1) return a.get(0);
        if (a.get(0) <= a.get(1))
        {
            a.remove(0);
        } else
        {
            a.remove(1);
        }
        return maxValue(a);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

The solution is bad as it destroys the input. At least, it should use a copy of the input, although that would make it slow and memory hungry.
Yep i wanted to mention that, but based on what the OP wrote(starting code) it’s what the assignment needs
0

Try this:

import java.util.List;
import static java.util.Math.*;
import java.util.NoSuchElementException;
import static java.util.Objects.*;

public static int maxValue( List<Integer> list )
{
    if( isNull( list ) ) throw new IllegalArgumentException( "list is null." );
    if( list.isEmpty() ) throw new NoSuchElementException( "Can't compute max of empty list." );

    var size = list.size();
    var head = list.get( 0 );
    var retValue = size == 1 ? head : max( head, maxValue( list.sublist( 1, size ) ); 
    return retValue;
}

List.subList() does not return a copy of the (sub)list, but a new view on the underlying list.

Comments

0

If the requirements permit, you could add a second parameter n, and pass the size of ArrayList.

   ...
   System.out.println(maxValue(arrlst, arrlst.size()));
   ...


public static int maxValue(ArrayList<Integer> a, int n) {
    if (n == 1)
        return a.get(0);

    return Math.max(a.get(n - 1), maxValue(a, n - 1));
}

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.