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, achievable when .
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:
- The only adding state is residue 1. If the computation starts in residue 1, it adds once and moves to residue 0. From residue 0, it moves to 2, then back to 0, never visiting 1 again.
- Thus, the maximum possible value is 1.
Tempting wrong path: assume the residue cycle allows multiple additions of 1. This breaks because the cycle never includes residue 1, so the addition stops after the first step.
Verification: For start = 0, end = 0, . , returns . has , returns 0. Total = 1.