Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: What is the maximum sum of a subarray with at most one element deleted from [1, -2, 3, -4, 5]? Run the code.

Problem: What is the maximum sum of a subarray with at most one element deleted from [1, -2, 3, -4, 5]? Run the code.
a = [1, -2, 3, -4, 5]
best = -10 ** 9
for skip in range(len(a) + 1):
    b = a[:skip] + a[skip + 1:] if skip < len(a) else a
    for i in range(len(b)):
        for j in range(i + 1, len(b) + 1):
            best = max(best, sum(b[i:j]))
print(best)
What is printed?
  1. A. 5
  2. B. 8
  3. C. 9
  4. D. 3

Correct answer: B. 8

Deleting −4 gives [1, −2, 3, 5], whose best subarray 3 + 5 = 8. Kadane without a deletion gives 5, summing all positives (two deletions) gives 9, and the whole array sums to 3.

More Coding Interview Problems questions

Exams that ask this topic