Question
Consider the following C function in which size is the number of elements in the array E:
int MyX(int *E, unsigned int size)
{
int Y = 0;
int Z;
int i, j, k;
for(i = 0; i < size; i++)
Y = Y + E[i];
for(i = 0; i < size; i++)
for(j = i; j < size; j++)
{
Z = 0;
for(k = i; k <= j; k++)
Z = Z + E[k];
if (Z > Y)
Y = Z;
}
return Y;
}
The value returned by the function MyX is the
Official answer and solution
- Official answer
- A
- From
- Official GATE 2014 answer key
Solution
Trace the logic of the nested loops to see how sub-array sums are computed and tracked in variable Y.
In the function MyX:
- The first loop calculates the sum of all elements in array
Eand stores it intoY: - The second set of loops has three indices:
iranges from to (starting index of sub-array).jranges fromito (ending index of sub-array).kranges fromitoj, computing the sum of elements in the sub-array and storing it intoZ:
- If ,
Yis updated to . - Because all pairs with are considered, every contiguous sub-array is examined.
- The final value in
Yis the maximum among the entire array sum and all sub-array sums, which is precisely the maximum possible sum of elements in any sub-array of arrayE.
A
Assuming the initial sum in Y forces the function to return only the full array sum, whereas subsequent sub-arrays can exceed it if negative numbers exist.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2014 Computer Science and Information Technology (CS) Session 1
- Question
- 51 of 65, printed as CS Q.41
- 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.