Data Structures & AlgorithmsHardProduct Company SDE · Kadane variants

Problem: What is the maximum subarray sum over all prefixes of [-2, 1, -3, 4]? Print the list of running maximum-subarray values with Kadane's algorithm. Run the code.

Problem: What is the maximum subarray sum over all prefixes of [-2, 1, -3, 4]? Print the list of running maximum-subarray values with Kadane's algorithm. Run the code.
a = [-2, 1, -3, 4]
best = cur = a[0]
res = [best]
for x in a[1:]:
    cur = max(x, cur + x)
    best = max(best, cur)
    res.append(best)
print(res)
What is printed?
  1. A. [-2, 1, -2, 4]
  2. B. [-2, 1, 1, 4]
  3. C. [-2, 1, 1, 1]
  4. D. [-2, -3, -1, 4]

Correct answer: B. [-2, 1, 1, 4]

After each prefix, the best subarray is -2, then 1, then still 1 (after adding -3 the best stays at 1), and finally 4.

More Coding Interview Problems questions

Exams that ask this topic