I’m working with recursion trying to become better at with it. My current activity is trying to program a recursive method that generates the maximum number of events one could schedule. Heres my method so far:
public int maxEvents(int n, int[] Start) {
if(n<=0) return 0;
if(n==1) return 1;
else return maxEvents(n-1, Start) + maxEvents(Start[n]-1, Start);
}
Basically my main method passes maxEvents an int n, which is the last Event. So say I have 4 events (1-4) then n would be 4. The next part is an array who’s value at the index is the time the event starts, and the index itself is when the event ends.
The preconditions are:
n >= 0
days and conventions go from 1 to n
Event n ends at (and includes) day n and begins at Start[n]
Begin[0] is unused
For all i from 1 to n, Begin[i] <= i ( Convention i can’t have a later beginning day than ending day, of course.)
At the end my method is supposed to return:
The maximum number of conventions you can host if you must select only from conventions 1 through n. (This set is empty if n = 0)
Some example input / outputs:
n = 3 Begin[1]=1 Begin[2]=1 Begin[3]=3
maxEvents=2
Or:
n = 5 Begin[1]=1 Begin[2]=1 Begin[3]=2 Begin[4]=3 Begin[5]=4
maxEvents=3
My two recursive calls should count the maximum number without inviting n, you can then chose from 1 to n-1. And count the maximum number inviting n, noting that Begin[n]-1 is the last convention that does not conflict with the beginning of convention n. Then I could take the max of the two, and return that.
I’ve tried using different if statements, saying something like:
if(“recursion call 1″>”recursion call 2”){
return “recursion call 1”;
}
And using something like “maxEvents(Start[n]-1, Start)” as one of my recursive calls (like used in my above code) however its not returning the correct values, like the ones I listed above. All in all I’m having trouble with the concept of recursion, and I know something is wrong with my recursive calls, so if someone could point me in the right direction that’d be great. Thanks!
Does this work?
The idea is that you are splitting into two mutually exclusive cases: one where the nth event is not included and another where nth event is included. Out of the two, you have to select the bigger. So adding the two is not correct – taking the max is the right way. But you have to also add a 1 to the second option to account for including the nth event.