原题链接在这里:https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/description/
题目:
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 <= 105
-104 <= arr[i] <= 104
题解:
Have oneDel to mark up to current index, what is the maximum if we already have one deleteion, initialized as 0.
Have noDel to mark up to current index, what is the maximum if we don't have any deletion, initialized as nums[0].
Then oneDel = Math.max(oneDel + arr[i], noDel), oneDel + arr[i] means it already has oneDel before, can't delete the current value. noDel means deleting the current value.
noDel = Math.max(noDe + arr[i], arr[i]).
Update the max result/
Time Complexity: O(n). n = arr.length.
Space: O(1).
AC Java:
1 class Solution { 2 public int maximumSum(int[] arr) { 3 if(arr == null || arr.length == 0){ 4 return 0; 5 } 6 7 int n = arr.length; 8 int oneDel = 0; 9 int noDel = arr[0]; 10 int max = arr[0]; 11 for(int i = 1; i < n; i++){ 12 oneDel = Math.max(oneDel + arr[i], noDel); 13 noDel = Math.max(noDel + arr[i], arr[i]); 14 max = Math.max(max, Math.max(oneDel, noDel)); 15 } 16 17 return max; 18 } 19 }标签:arr,noDel,1186,max,Sum,Maximum,maximum,subarray,oneDel From: https://www.cnblogs.com/Dylan-Java-NYC/p/18181884