Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Kadane's algorithm (Java):

Problem: Kadane's algorithm (Java):
int best = 0, cur = 0;            // line 1
for (int x : a) {
    cur = Math.max(x, cur + x);    // line 3
    best = Math.max(best, cur);
}
return best;
For a = {-5, -2, -9} it returns 0 instead of −2. What is the fix?
  1. A. Change line 3 to cur = cur + x
  2. B. Initialise best to a[0] (or Integer.MIN_VALUE) instead of 0 in line 1
  3. C. Initialise cur to Integer.MIN_VALUE only
  4. D. Reset cur to 0 whenever it becomes negative

Correct answer: B. Initialise best to a[0] (or Integer.MIN_VALUE) instead of 0 in line 1

best = 0 assumes the empty subarray is allowed. Starting best at a[0] (and cur at 0 or a[0]) returns the largest element −2 for all-negative input. Resetting cur to 0 is the same 'empty allowed' mistake; changing line 3 breaks the restart logic.

More Coding Interview Problems questions

Exams that ask this topic