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
View worked solution
Answer: A
Let us analyze the behavior of the function MyX step-by-step:
-
Initialization and First Loop:
This loop calculates the sum of all elements in the array and stores it in . Thus, initially, . Note that the entire array is itself a valid sub-array.int Y = 0; for(i = 0; i < size; i++) Y = Y + E[i]; -
Nested Loops for Sub-arrays:
The outer loops with indices and define the boundaries of every possible contiguous sub-array of . The innermost loop with index computes the sum of the elements in this sub-array and stores it in .for(i = 0; i < size; i++) for(j = i; j < size; j++) { Z = 0; for(k = i; k <= j; k++) Z = Z + E[k]; ... } -
Updating the Maximum Sum:
If the sum of the current sub-array () is strictly greater than the current maximum sum (), then is updated to .if(Z > Y) Y = Z;
Since 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 (which is the brute-force solution to the Maximum Subarray Sum problem).
Free practice · Your answers on this page are not saved.
