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 Deletion INPUT arr = [1, -3, 2, 1, -1] 1 i=0 -3 i=1 2 i=2 1 i=3 -1 i=4 Selected subarray Not selected / Deleted DP Variables: maxEndHere: max sum ending at i maxEndHereDel: max sum with one deletion ending at i maxSoFar: global maximum ALGORITHM STEPS 1 Initialize maxEndHere = maxEndHereDel = maxSoFar = arr[0] 2 For each element i=1 to n-1 Save prev maxEndHere 3 Update DP values maxEndHere = max(arr[i], maxEndHere + arr[i]) maxEndHereDel = max( prev, maxEndHereDel+arr[i]) 4 Update global max maxSoFar = max(maxSoFar, maxEndHere, maxEndHereDel) Iteration Trace (Space O(1)) i=1: mEH=max(-3,-2)=-2 i=2: mEH=max(2,0)=2 i=3: mEH=max(1,3)=3 i=4: mEH=max(-1,2)=2, mEHD=4 FINAL RESULT Optimal subarray: [2, 1] or [2, 1, -1] with -1 deleted 2 + 1 + -1 (deleted element shown crossed) Output: 4 [OK] Sum = 2 + 1 + 1 = 4 Space Optimized Time: O(n) | Space: O(1) Key Insight: At each position, we track two values: (1) maximum subarray sum ending here with NO deletion, and (2) maximum sum ending here with exactly ONE deletion. For option 2, we either delete the current element (use previous no-deletion sum) or keep it (add to previous one-deletion sum). Space optimization: Only O(1) variables needed instead of O(n) arrays! TutorialsPoint - Maximum Subarray Sum with One Deletion | Space Optimized DP
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