Skip to content
Official PYQ · 2014

GATE CS 2014 Set 1 Q41 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

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
View worked solution

Answer: A

Let us analyze the behavior of the function MyX step-by-step:

  1. Initialization and First Loop:
    int Y = 0;
    for(i = 0; i < size; i++) 
        Y = Y + E[i];
    This loop calculates the sum of all elements in the array EE and stores it in YY. Thus, initially, Y=∑p=0size−1E[p]Y = \sum_{p=0}^{\text{size}-1} E[p]. Note that the entire array is itself a valid sub-array.
  2. Nested Loops for Sub-arrays:
    for(i = 0; i < size; i++) 
        for(j = i; j < size; j++) { 
            Z = 0; 
            for(k = i; k <= j; k++) 
               Z = Z + E[k];
            ...
        }
    The outer loops with indices ii and jj define the boundaries of every possible contiguous sub-array E[i…j]E[i \dots j] of EE. The innermost loop with index kk computes the sum of the elements in this sub-array E[i…j]E[i \dots j] and stores it in ZZ.
  3. Updating the Maximum Sum:
    if(Z > Y) 
       Y = Z;
    If the sum of the current sub-array (ZZ) is strictly greater than the current maximum sum (YY), then YY is updated to ZZ.

Since YY is initialized to the sum of the entire array and is updated whenever a larger sub-array sum is found, the function eventually returns the maximum possible sum of elements in any sub-array of array EE (which is the brute-force solution to the Maximum Subarray Sum problem).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions