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: arr =[-1,-1,-1,-1]Output: -1Explanation: 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.
To find the maximum subarray sum with at most one deletion, we use dynamic programming to track two states: the maximum sum ending at each position without deletion, and the maximum sum ending at each position with one deletion. This allows us to consider both keeping and deleting an element for the best result.
classSolution {
public:int maximumSum(vector<int>& arr) {
int ans = arr[0], keep = arr[0], del = INT_MIN;
for (int i =1; i < arr.size(); ++i) {
del = max(keep, del + arr[i]);
keep = max(arr[i], keep + arr[i]);
ans = max(ans, max(keep, del));
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
funcmaximumSum(arr []int) int {
ans, keep, del:=arr[0], arr[0], -1<<31fori:=1; i < len(arr); i++ {
del = max(keep, del+arr[i])
keep = max(arr[i], keep+arr[i])
ans = max(ans, max(keep, del))
}
returnans}
func max(a, bint) int { ifa > b { returna }; returnb }
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintmaximumSum(int[] arr) {
int ans = arr[0], keep = arr[0], del = Integer.MIN_VALUE;
for (int i = 1; i < arr.length; i++) {
del = Math.max(keep, del + arr[i]);
keep = Math.max(arr[i], keep + arr[i]);
ans = Math.max(ans, Math.max(keep, del));
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaximumSum(arr: IntArray): Int {
var ans = arr[0]
var keep = arr[0]
var del = Int.MIN_VALUE
for (i in1 until arr.size) {
del = maxOf(keep, del + arr[i])
keep = maxOf(arr[i], keep + arr[i])
ans = maxOf(ans, keep, del)
}
return ans
}
}
1
2
3
4
5
6
7
8
defmaximumSum(arr: list[int]) -> int:
ans = keep = arr[0]
del_ = float('-inf')
for i in range(1, len(arr)):
del_ = max(keep, del_ + arr[i])
keep = max(arr[i], keep + arr[i])
ans = max(ans, keep, del_)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnmaximum_sum(arr: Vec<i32>) -> i32 {
letmut ans = arr[0];
letmut keep = arr[0];
letmut del =i32::MIN;
for i in1..arr.len() {
del = keep.max(del + arr[i]);
keep = arr[i].max(keep + arr[i]);
ans = ans.max(keep).max(del);
}
ans
}
}