Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track 'no deletion yet' and 'one deletion used' states.

Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track 'no deletion yet' and 'one deletion used' states.
def max_del(a):
    keep, dele, best = a[0], float("-inf"), a[0]
    for x in a[1:]:
        dele = max(dele + x, keep)
        keep = max(keep + x, x)
        best = max(best, keep, dele)
    return best
print(max_del([3, -1, 4, -6, 2, 5]), max_del([-4, -2, -7]), max_del([2, -9, 3, -1, 4]))
What is printed?
  1. A. 13 -2 6
  2. B. 13 0 8
  3. C. 13 -2 8
  4. D. 7 -2 8

Correct answer: C. 13 -2 8

dele (ending here, one element already removed) either extends a previous dele, or deletes x itself after the best keep ending just before. keep is plain Kadane. [3, −1, 4, −6, 2, 5]: delete −6 → 3 − 1 + 4 + 2 + 5 = 13 (Kadane alone gives 7). All negative: the best single element −2 (deleting it would leave an empty subarray, not 0). [2, −9, 3, −1, 4]: delete −9 → 8. O(n).

More Coding Interview Problems questions

Exams that ask this topic