Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern

Kadane's algorithm runs on the array [-9, 1, 7, 5, 7, -3, 0, -7, 1] to find the maximum sum of a contiguous subarray. What sum does it return?

  1. A. 20
  2. B. 23
  3. C. 7
  4. D. 2

Correct answer: A. 20

Tracing Kadane's algorithm (reset the running sum to the current element whenever it drops to zero or below, else extend it) gives a best contiguous sum of 20, from index 1 to 4. 2 is the sum of the whole array (wrong when some prefix should be dropped), and 7 is just the single largest element, which ignores combining it with neighbours.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic