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.
class Solution:
def maximumSum(self, arr: list[int]) -> int:
n = len(arr)
# left[i]: max sum of subarray ending at i without deletion
left = [0] * n
# right[i]: max sum of subarray starting at i without deletion
right = [0] * n
# Calculate left array
left[0] = arr[0]
max_so_far = arr[0]
for i in range(1, n):
left[i] = max(arr[i], left[i-1] + arr[i])
max_so_far = max(max_so_far, left[i])
# Calculate right array
right[n-1] = arr[n-1]
curr_max = arr[n-1]
for i in range(n-2, -1, -1):
right[i] = max(arr[i], right[i+1] + arr[i])
curr_max = max(curr_max, right[i])
# Calculate max sum with one deletion
max_sum = max_so_far # Initialize with max sum without deletion
for i in range(1, n-1):
max_sum = max(max_sum, left[i-1] + right[i+1])
return max_sum
Problem Understanding:
Naive Approach:
Optimal Approach:
left
and right
.
left[i]
stores the maximum subarray sum ending at index i
without any deletions.right[i]
stores the maximum subarray sum starting at index i
without any deletions.i
(excluding the first and last), we consider the possibility of deleting the element at i
. The maximum subarray sum with one deletion can be calculated as left[i-1] + right[i+1]
. This represents the sum of the maximum subarray ending at i-1
and the maximum subarray starting at i+1
, effectively deleting element i
.max_so_far
(maximum subarray sum without deletion) and the maximum sum calculated by considering each element's deletion.Code Implementation Details:
left
and right
arrays using Kadane's algorithm.max_sum
variable is updated to store the maximum sum found so far.For arr = [1, -2, 0, 3]
,
left
array will be computed as [1, -1, 0, 3]
right
array will be computed as [1, 0, 3, 3]
-2
: max sum will be left[0] + right[2] = 1 + 3 = 4
0
: max sum will be left[1] + right[3] = -1 + 3 = 2
left
and right
are also considered which are 1
, 0
, 3
and 1
,0
,3
,3
respectively.4
.All Negative Numbers:
Single Element Array:
Array with Zeros:
Empty Array:
left
array takes O(n) time.right
array takes O(n) time.left
array requires O(n) space.right
array requires O(n) space.