501 views
0 votes
0 votes

Original Question  - here

 

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.

 

====================================================================================

 

Can someone trace the code by taking some arbitrary values in the array and show how to do this? Thank you!

1 Answer

Best answer
1 votes
1 votes

What is the meaning of sub-array?

 for(i = 0; i< size; i++) 
          Y = Y + E[i];

therefore Y is sum of all elements of E 

 

Z = 0; 
for(k = i; k <= j; k++) 
      Z = Z + E[k];

therefore Z is sum of all the elements on that sub array only 

 

if(Z > Y) 
   Y = Z;

 therefore updating Y with sum of all the elements on that sub array when it is grater than y, 
means Y = maximum possible sum of elements in any sub-array of array E.

 

your doubt is how got that sub array?

therefore k is a every possible sub array ==> y returns maximum possible ( sum of elements in any sub-array of array E. )

 

if you didn't get this, then follow this method for understanding...

 

Let A is array of 5 elements, A=[a,b,c,d,e]

 

what are the all possible sub-array's ?

 

1) a, ab, abc, abcd, abcde

2) b, bc, bcd, bcde

3) c, cd, cde

4) d, de

5) e

---------------------------------

i=1 to n -----> getting 5 rows

j=i to n

k=i to j ------> dividing into sub array

selected by

Related questions