#1186
Maximum Subarray Sum with One Deletion
MediumArrayDynamic ProgrammingDynamic ProgrammingKadane's Algorithm
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses dynamic programming to keep track of the maximum subarray sums with and without deletion, allowing us to compute the result in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two variables, max_sum and max_sum_with_deletion, to track the maximum sums.
- 2Step 2: Iterate through the array, updating max_sum to be the maximum of the current element or the current element plus the previous max_sum.
- 3Step 3: Update max_sum_with_deletion to be the maximum of itself or max_sum (without deletion) plus the current element.
solution.py10 lines
1def maxSumAfterOneDeletion(arr):
2 max_sum = arr[0]
3 max_sum_with_deletion = 0
4 for i in range(1, len(arr)):
5 max_sum = max(arr[i], max_sum + arr[i])
6 max_sum_with_deletion = max(max_sum_with_deletion + arr[i], max_sum)
7 return max(max_sum, max_sum_with_deletion)
8
9# Example usage
10print(maxSumAfterOneDeletion([1,-2,0,3])) # Output: 4ℹ
Complexity note: This complexity is linear because we only traverse the array once, maintaining a constant amount of additional space.
- 1Understanding how to maintain two states (with and without deletion) is crucial for dynamic programming problems.
- 2Recognizing that we can build on previous results helps in optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.