Data Structures & AlgorithmsHardProduct Company SDE · Kadane variants

Problem: Kadane's algorithm is started with best = 0 and a running sum initialised to 0, then applied to an array where every number is negative, such as [-5, -2, -9]. The problem requires a non-empty subarray. What should the answer be?

  1. A. 0, since the empty subarray sums to 0
  2. B. -2, the largest element
  3. C. -16, the sum of everything
  4. D. -9, the last element

Correct answer: B. -2, the largest element

Initialising best to 0 wrongly admits the empty subarray. The correct answer is the maximum element, here -2, so best must start at the first element or negative infinity.

More Coding Interview Problems questions

Exams that ask this topic