[LeetCode] Maximum Subarray Sum with One Deletion

1186. Maximum Subarray Sum with One Deletion

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.

  • kadane’s algorithm solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int maximumSum(vector<int>& A) {
int res = INT_MIN, n = A.size();
vector<int> front(n), back(n);

for(int i = 0, kadane = -1e5; i < n; i++) {
kadane = max(kadane + A[i], A[i]);
front[i] = kadane;
res = max(res, kadane);
}

for(int i = n - 1, kadane = -1e5; i >= 0; i--) {
kadane = max(kadane + A[i], A[i]);
back[i] = kadane;
res = max(res, kadane);
}

for(int i = 1; i < n - 1; i++) {
res = max(res, front[i-1] + back[i+1]);
}

return res;
}
};
  • dp solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int maximumSum(vector<int>& A) {
int res = INT_MIN, n = A.size();
if(n == 1) return A[0];
int drop = max(A[0] + A[1], A[0]);
int notDrop = max(A[0] + A[1], A[1]);
res = max({res, drop, notDrop});

for(int i = 2; i < n; i++) {
drop = max(notDrop, drop + A[i]);
notDrop = max(notDrop + A[i], A[i]);
res = max({res, drop, notDrop});
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/maximum-subarray-sum-with-one-deletion/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.