LeetCode 1186. Maximum Subarray Sum with One Deletion(java)

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

maximum subarray sum的變形,變形在於,答案在於咩有刪除和有刪除。沒有刪除:以每個index爲結尾走一遍,得到最大值。有刪除:以每個index爲結尾和開頭走一遍,然後刪除i的結果 res = Math.max(res, end[i-1] + start[i+1]).
class Solution {
    public int maximumSum(int[] arr) {
        if (arr.length == 0) return 0;
        int[] end = new int[arr.length];
        int[] start = new int[arr.length];
        end[0] = arr[0];
        int res = end[0];
        for (int i = 1; i < arr.length; i++) {
            end[i] = Math.max(end[i-1] + arr[i], arr[i]);
            res = Math.max(res, end[i]);
        }
        start[arr.length - 1] = arr[arr.length - 1];
        for (int i = arr.length - 2; i >= 0; i--) {
            start[i] = Math.max(start[i+1] + arr[i], arr[i]);
        }
        
        for (int i = 1; i < arr.length - 1; i++) {
            if (arr[i] < 0) {
                res = Math.max(res, end[i-1] + start[i+1]);
            }
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章