Maximum Subarray Sum with One Deletion
LeetCode 1288 | Difficulty: Mediumβ
MediumProblem Descriptionβ
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.
Example 1:
Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.
Example 3:
Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
Constraints:
- `1 <= arr.length <= 10^5`
- `-10^4 <= arr[i] <= 10^4`
Topics: Array, Dynamic Programming
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
Solutionsβ
Solution 1: C# (Best: 148 ms)β
| Metric | Value |
|---|---|
| Runtime | 148 ms |
| Memory | 41.3 MB |
| Date | 2022-01-26 |
public class Solution {
public int MaximumSum(int[] arr) {
int oneDelete = 0, noDelete = arr[0];
int max = arr[0];
for(int i=1;i<arr.Length;i++)
{
oneDelete = Math.Max(oneDelete+arr[i], noDelete);
noDelete = Math.Max(noDelete+arr[i], arr[i]);
max = Math.Max(max, Math.Max(oneDelete, noDelete));
}
return max;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Dynamic Programming | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.
- LeetCode provides 3 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: How to solve this problem if no deletions are allowed ?
Hint 2: Try deleting each element and find the maximum subarray sum to both sides of that element.
Hint 3: To do that efficiently, use the idea of Kadane's algorithm.