int func(int start, int end){
int length=end+1-start;
if((length<1)||(start<0)||(end<0)){ return(0); }
if(length%3==0){
return(func(start+1, end));
} else if(length%3==1){
return(1+func(start, end-1));
} else {
return(func(start+2, end));
}
}The maximum possible value that can be returned from this function is ____________. (answer in integer)
Note: Ignore syntax errors (if any) in the function.
1.00
Step-by-Step Solution
Insight: The function's return value depends on length % 3. The only branch that adds 1 is length % 3 == 1, which transitions the length to length - 1 (residue 0). From residue 0, the sequence of residues is 0 -> 2 -> 0 -> 2..., never returning to 1. Thus, 1 is added at most once.
Exam route: Let be the initial length. If : adds 1, new . If : adds 0, new . If : adds 0, new . The residue 1 is visited at most once. The maximum return value is 1.
Learning route:
- This is a modulo state-transition recursion question, recognisable because the branch taken and the amount subtracted from the effective length depend on
length % 3. - Define . The base case returns 0 if or if an index is negative.
- Determine how each branch changes :
- If , the call is
func(start+1, end), so new length is . - If , the return is
func(start, end-1), so new length is . - If , the call is
func(start+2, end), so new length is .
- Convert to residue transitions:
add 1, .
add 0, .
add 0, .
- The only adding state is residue 1. If the computation starts in residue 1, it adds once and moves to residue 0. From 0, it goes to 2, then back to 0, never visiting 1 again.
- Therefore, the maximum possible value returned is 1.
Tempting wrong path: assume the function can add 1 multiple times by cycling through residues. This breaks because the transitions are strictly , and residue 1 is never revisited.
Verification: If (residue 1), it adds 1, new (residue 0). Next, adds 0, new (residue 2). Next, adds 0, new . Base case returns 0. Total sum = 1.