Maximum Subarray Sum with One Deletion - Problem

Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion.

In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.

Note that the subarray needs to be non-empty after deleting one element.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,-3,2,1,-1]
Output: 4
💡 Note: We can choose subarray [2,1,-1] and delete -1 to get [2,1] with sum = 3. Or choose [1,-3,2,1] and delete -3 to get [1,2,1] with sum = 4.
Example 2 — No Deletion Needed
$ Input: arr = [1,-2,0,3]
Output: 4
💡 Note: We can choose subarray [1,-2,0,3] and delete -2 to get [1,0,3] with sum = 4. Or just take [3] without deletion.
Example 3 — Single Element
$ Input: arr = [-1]
Output: -1
💡 Note: We must return at least one element. Since we only have [-1], we cannot delete it, so return -1.

Constraints

  • 1 ≤ arr.length ≤ 105
  • -104 ≤ arr[i] ≤ 104

Visualization

Tap to expand
Maximum Subarray Sum with One Deletion1-321-101234Selected Subarray [1,-3,2,1]Delete -3Remaining: [1,2,1] = 1 + 2 + 1 = 4Maximum Sum: 4
Understanding the Visualization
1
Input Array
Array [1,-3,2,1,-1] with negative elements
2
Find Best Subarray
Consider subarrays with 0 or 1 deletion
3
Output Maximum
Return 4 by deleting -3 from [1,-3,2,1]
Key Takeaway
🎯 Key Insight: Track two DP states simultaneously - maximum sum with 0 deletions and 1 deletion
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
73.9K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen