Maximum Subarray Sum with One Deletion - Problem
Given an array of integers, find the maximum sum of a contiguous subarray where you can optionally delete at most one element to maximize the sum.
Think of it this way: you want to select a contiguous portion of the array (a subarray) and then have the option to remove one troublesome element from it to get the highest possible sum. The resulting subarray must still contain at least one element.
Goal: Return the maximum possible sum after applying this strategy.
Example: For array [1, -2, 0, 3], you could take the entire array and delete -2 to get sum 1 + 0 + 3 = 4, or just take [3] for sum 3. The maximum is 4.
Input & Output
example_1.py โ Basic Case
$
Input:
[1, -2, 0, 3]
โบ
Output:
4
๐ก Note:
We can take the entire array [1, -2, 0, 3] and delete -2 to get [1, 0, 3] with sum = 4. This is better than any subarray without deletion.
example_2.py โ No Deletion Needed
$
Input:
[1, -2, -2, 3]
โบ
Output:
3
๐ก Note:
The best strategy is to take the subarray [3] without any deletion. Deleting one element from longer subarrays doesn't improve the sum.
example_3.py โ All Negative Except One
$
Input:
[-1, -1, -1, -1]
โบ
Output:
-1
๐ก Note:
Since all elements are negative, we must take at least one element. The best choice is any single element, giving us -1.
Constraints
- 1 โค arr.length โค 105
- -104 โค arr[i] โค 104
- The resulting subarray must be non-empty after deletion
Visualization
Tap to expand
Understanding the Visualization
1
Initialize base case
First element: noDelete[0] = arr[0], oneDelete[0] = 0
2
Process each element
For each position, calculate both DP states based on previous optimal values
3
Update maximum
Track the best result seen so far from either state
4
Return optimal
The answer is the maximum value across all positions and both states
Key Takeaway
๐ฏ Key Insight: Use two DP states to track optimal subarrays with and without deletion, building solutions incrementally in linear time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code