#1186
Medium Algorithms Maximum subarray sum with one deletion
Array Dynamic Programming
46.8% acceptance
Feb 25, 2026
2017
81
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn maximum_sum(arr: Vec<i32>) -> i32 {
let n = arr.len();
// dp_no[i] = max subarray sum ending at i without deletion
// dp_del[i] = max subarray sum ending at i with one deletion used
let mut dp_no = arr[0];
let mut dp_del = i32::MIN / 2;
let mut ans = arr[0];
for i in 1..n {
let new_del = (dp_del + arr[i]).max(dp_no); // extend deletion or delete arr[i]
let new_no = (dp_no + arr[i]).max(arr[i]);
dp_del = new_del;
dp_no = new_no;
ans = ans.max(dp_no).max(dp_del);
}
ans
}
}