Data Structures & AlgorithmsVery hardProduct-company MCQ pattern

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

  1. A. 8
  2. B. 13
  3. C. 16
  4. D. 12

Correct answer: B. 13

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