GATE / CS ARCHIVE

GATE CSE 2014 SET 1 / QUESTION 41

GATE CSE 2014 Set 1 Q41

Programming in C · Arrays & Strings · Full GATE CSE 2014 Set 1 paper

GATE 2014 Set 1, Q41 2 marks · MCQ
Report issue

Arrays & Strings

Question 41, GATE 2014: In C, MyX(int *E,unsigned int size) first sets Y=0 and adds every E[i] to Y. It then loops i=0..size−1 and j=i..size−1, initializes Z=0, sums E[k] for k=i..j, and replaces Y by Z if Z>Y. It returns Y. What does it return? A: Maximum sum of a contiguous subarray. B: Maximum element in a subarray. C: Sum of maximum elements of all subarrays. D: Sum of all array elements.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

1. Method and setup. Each ordered index pair i≤j describes one nonempty contiguous subarray. The innermost loop computes its sum from scratch. The running variable Y retains the largest sum seen; initializing it to the whole-array sum ensures a valid candidate even when every entry is negative, unlike initializing the final maximum to zero.

2. Work through the result and its assumptions. Y starts as the sum of the whole array, itself a valid nonempty contiguous subarray. Every pair i≤j is then enumerated and Z sums exactly E[i..j]; Y is replaced whenever this sum is larger. Thus the final Y is the maximum nonempty subarray sum, A. This assumes a nonempty valid array, representable indices and no signed arithmetic overflow; for an empty array the routine returns 0.

Original paper, page 18 · Answer key