GATE / CS ARCHIVE

GATE CSE 2016 SET 2 / QUESTION 37

GATE CSE 2016 Set 2 Q37

Programming in C · Recursion · Full GATE CSE 2016 Set 2 paper

GATE 2016 Set 2, Q37 2 marks · NAT
Report issue

Recursion

Question 37, GATE 2016: Code: int f(int*p,int n){if(n<=1)return 0; else return max(f(p+1,n-1),p[0]-p[1]);} int main(){int a[]={3,5,2,6,4};printf("%d",f(a,5));}. max returns the greater argument. Find the printed value.
Tap to enlarge
Answer & solution

Official answer: 3.0 : 3.0

Our answer: 3

Step through it (13 steps)

The recurrence returns max(0, p[0]−p[1],..., p[n−2]−p[n−1]). For3, 5, 2, 6, 4 the adjacent differences are−2, 3,−4, 2; the maximum with 0 is 3.

Unwind from the end: the one-element suffix returns 0; suffix [6,4] returns max(0,2)=2; [2,6,4] returns max(2,−4)=2; [5,2,6,4] returns max(2,3)=3; the full array returns max(3,−2)=3. The function considers adjacent drops, not arbitrary pairs or absolute differences.

Original paper, page 35 · Answer key