Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern

Kadane's algorithm runs on the array [2, -8, 4, -2, 4, -5, -2] to find the maximum sum of a contiguous subarray. What sum does it return?

  1. A. 4
  2. B. 11
  3. C. 6
  4. D. -7

Correct answer: C. 6

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 6, from index 2 to 4. -7 is the sum of the whole array (wrong when some prefix should be dropped), and 4 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