Question
Consider the following ANSI-C function.
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.
Official answer and solution
- Official answer
- 1
- From
- Official GATE 2026 answer key
Solution
Track how length = end + 1 - start changes modulo 3 in each recursive branch.
Let . Whenever or or , func returns . For :
- If : the
elsebranch callsfunc(start + 2, end), which reduces by without adding to the return value, giving . - If : the first branch calls
func(start + 1, end), which reduces by without adding to the return value, giving .
Thus any call starting with or alternates between and (decreasing by , then , then , ...) until , returning ! - If : the
else ifbranch returns1 + func(start, end - 1), which adds and reduces by to . By the case above, the recursive call with always returns !
Therefore, func returns at most for any inputs.
1
Assuming the length % 3 == 1 branch can be visited multiple times when in fact it transitions immediately to length % 3 == 0, which then cycles between and .
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2026 Computer Science and Information Technology - Session 2 (CS2)
- Question
- 61 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.