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

Choose one option
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:

  1. The first loop calculates the sum of all elements in array E and stores it into Y:
    Y=∑i=0size−1E[i]Y = \sum_{i=0}^{\text{size}-1} E[i]
  2. The second set of loops has three indices:
    • i ranges from 00 to size−1\text{size}-1 (starting index of sub-array).
    • j ranges from i to size−1\text{size}-1 (ending index of sub-array).
    • k ranges from i to j, computing the sum of elements in the sub-array E[i..j]E[i..j] and storing it into Z:
      Z=∑k=ijE[k]Z = \sum_{k=i}^j E[k]
  3. If Z>YZ > Y, Y is updated to ZZ.
  4. Because all pairs (i,j)(i, j) with 0≤i≤j<size0 \le i \le j < \text{size} are considered, every contiguous sub-array is examined.
  5. The final value in Y is 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 array E.
Final answer

A

Common trap

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.