Home » Programming & Data Structure » Programming and data structure miscellaneous » Question

Programming and data structure miscellaneous

Programming & Data Structure

  1. 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
    1. maximum possible sum of elements in any sub-array of array E.
    2. maximum element in any sub-array of array E.
    3. sum of the maximum elements in all possible sub-arrays of array E.
    4. the sum of all the elements in the array E.
Correct Option: A

Clearly the code segment : for
(i = 0; i < size; i + +) Y = Y + E [i]
Computes the sum of all element in the array E.
Note : As the array E may contain negative elements, the sum of elements of subarray of E may be greater than the sum of all elements in the array E. Now, comes the nested i, j, k loops :
‘i’ changes the starting of the subway.
‘j’ changes the end position of the subarray. ‘k’ loop is used to compute sum of elements of the particular subarray. The sum of subarray is stored in z and is compared to the earlier max sum Y. Finally the larger sum gets stored in Y.

This can be easily seen how sum of subarray is computed with different values of i and j.



Your comments will be displayed only after manual approval.