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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code