• edited by
629 views
0 0 votes

Consider the following code, in which $\text{A}$ is an array indexed from $0.$

function foo (A , n) {
    m = A [0] ;
    x = 0 ;
    for i = 0 to n – 1  {
        x = x + A [i] ;
        if (m < x)  {
            m = x ;
        }
        if (x < 0)  {
            x = 0 ;
        }

    }
    return (m) ;
}

If $\text{A}=[-12, -3, 5, 10, 8, -16, -23, 12, -5, 7]$, what will $\textsf{foo(A, 10)}$ return?

  1. $23$
  2. $17$
  3. $-17$
  4. $35$

1 Answer

0 0 votes

Answer: A

This is very famous Kadane’s Algorithm that is used to find the maximum sum of contiguous subarray.

Idea of this algorithm is first initialize the max sum as the initial element and current sum to 0. Now iterate through the array and update the current sum. If current sum is greater than the max sum then update the max sum to the current sum. If our current sum gets below 0 then just update the current sum to 0 and move ahead.

To know more about this algorithm refer : https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/

For A = [-12, -3, 5, 10, 8, -16, -23, 12, -5, 7], largest subarray sum would be 23 for subarray [5, 10, 8].

 

Position:
Show:

Related questions

2 2 votes
1 1 answer
455
455 views
admin asked Jul 23, 2022
455 views
There are two longest subsequences, not necessarily contiguous, common to the strings $\text{“ARTIFICIAL"}$ and $\text{“INTELLIGENCE."}$ They are $\text{“IIC"}$ and $\tex...
1 1 vote
2 2 answers
654
654 views
admin asked Jul 23, 2022
654 views
The roots of the polynomial $p(x)=x^{4}-2x^{3}-2x^{2}+8x-8$ are:$1, -1, 2, 2+3 i$$1+i, 1-i, 2, -2$$1, -1+i, 2, 2+3 i$$1+i, -1+i, 2, -2$
1 1 vote
1 1 answer
443
443 views
admin asked Jul 23, 2022
443 views
A student has an average score of $80$ from her first four Mathematics tests, and $88$ from her first five Physics tests. How much must she score in her upcoming tests to...
1 1 vote
1 1 answer
539
539 views
admin asked Jul 23, 2022
539 views
A binary tree starts with a single root node at the top of the tree. Each node can have either a left child or a right child, or both, or neither. The children of a node ...