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.

 

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:


Solution:

class Solution {
    public int maximumSum(int[] arr) {
        int n = arr.length;
        // dp[i][0] = maxSum of subarray end at i, without dropping previous element
        // dp[i][1] = maxSum of subarray end at i, with dropped previous element
        int[][] dp = new int[n][2];
        int max = arr[0];
        dp[0][0] = arr[0];
        dp[0][1] = arr[0];
        for (int i = 1; i < n; i ++) {
            dp[i][0] = Math.max(arr[i], arr[i] + dp[i - 1][0]);
            if (i > 1) {
                dp[i][1] = arr[i] + Math.max(dp[i - 2][0], dp[i - 1][1]);
            } else {
                dp[i][1] = arr[i];
            }
            max = Math.max(max, Math.max(dp[i][0], dp[i][1]));
        }
        // for (int[] d : dp) System.out.println(Arrays.toString(d));
        return max;
    }
}