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
Maximum Subarray Sum with One DeletionInput Array: [1, -2, 0, 3]1-203DP State 1: No Deletion Allowed1-103โ† Kadane's algorithmDP State 2: One Deletion Allowed0114โ† Extended Kadane'sState TransitionsnoDelete[i] = max(arr[i], noDelete[i-1] + arr[i])oneDelete[i] = max(noDelete[i-1], oneDelete[i-1] + arr[i])โ€ข Delete current: noDelete[i-1]โ€ข Keep current: oneDelete[i-1] + arr[i]โ€ข Take maximum of both optionsFinal AnswerMaximum from both states: 4Achieved by: [1, -2, 0, 3] โ†’ delete -2 โ†’ [1, 0, 3]Sum: 1 + 0 + 3 = 4Optimal pathTime: O(n) | Space: O(n) โ†’ can be optimized to O(1)
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.
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
42.0K Views
Medium-High Frequency
~22 min Avg. Time
1.5K 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