Maximum Subarray Sum with One Deletion — LeetCode 1186 Python Solution
- Problem
- #1186
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- 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.
Python solution
class Solution:
def maximumSum(self, arr: List[int]) -> int:
n = len(arr)
left = [0] * n
right = [0] * n
s = 0
for i, x in enumerate(arr):
s = max(s, 0) + x
left[i] = s
s = 0
for i in range(n - 1, -1, -1):
s = max(s, 0) + arr[i]
right[i] = s
ans = max(left)
for i in range(1, n - 1):
ans = max(ans, left[i - 1] + right[i + 1])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1186. Maximum Subarray Sum with One Deletion is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1186. Maximum Subarray Sum with One Deletion?
- LeetCode 1186. Maximum Subarray Sum with One Deletion is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1186. Maximum Subarray Sum with One Deletion?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1186. Maximum Subarray Sum with One Deletion?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1186. Maximum Subarray Sum with One Deletion cover?
- LeetCode 1186. Maximum Subarray Sum with One Deletion is tagged Array and Dynamic Programming on LeetCode.