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.
Constraints:
1 <= arr.length <= 10^5
-10^4 <= arr[i] <= 10^4
Solution: DP
First, handle the special case: all numbers are negative, return the max one.
s0 = max subarray sum ends with a[i]
s1 = max subarray sum ends with a[i] with at most one deletion
whenever s0 or s1 becomes negative, reset them to 0.
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua class Solution { public: int maximumSum(vector<int>& arr) { int m = *max_element(begin(arr), end(arr)); if (m <= 0) return m; int s0 = 0; int s1 = 0; int ans = 0; for (int a : arr) { s1 = max(s0, s1 + a); s0 += a; ans = max(ans, max(s0, s1)); if (s0 < 0) s0 = 0; if (s1 < 0) s1 = 0; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment