#1186

Maximum Subarray Sum with One Deletion

Medium Kadane with two states

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the largest sum of a non-empty subarray when you are allowed to delete at most one element from it (it must stay non-empty).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: best subarray sum if you may delete one element from it.

Why this works: track two values per index: best sum ending here with no deletion, and with one deletion already used.

Example: [1, -2, 0, 3]

at 3: no-deletion best = 0 + 3 = 3with deletion of -2: 1 + 0 + 3 = 4answer 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Letting the "deleted" state be an empty subarray, which wrongly returns 0 for all-negative input.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Kadane, Dutch Flag & Moore's Voting
🎬 Episodes 11–13: video coming soon