Maximum Subarray Sum with One Deletion
You are given an array of integers nums. Your task is to find the maximum possible sum of a non-empty subarray, with the option to delete at most one element from that subarray. If you choose to delete an element, the remaining elements must still form a non-empty subarray.
[ "[-1, -5, -2]" ]
Explanation. The maximum sum is obtained from the subarray `[-1]`, which has a sum of `-1`. Deleting any element from a larger subarray of negative numbers would result in a smaller sum (e.g., deleting `-5` from `[-1, -5, -2]` gives `[-1, -2]` with sum `-3`).
[ "[-4, -5]" ]
Explanation. The maximum sum is obtained from the subarray `[-4]` with a sum of `-4`. Deleting `-5` from `[-4, -5]` results in `[-4]` (sum `-4`). Deleting `-4` from `[-4, -5]` results in `[-5]` (sum `-5`).
[ "[-1, -2, 0, 3]" ]
Explanation. Consider the subarray `[0, 3]`, which has a sum of `3`. This is greater than `[1, -2, 0, 3]` deleting `-2` to get `[1, 0, 3]` (sum `4`) is wrong. `nums = [-1, -2, 0, 3]` -> `[0,3]` sum 3. `[3]` sum 3. The input was `[1, -2, 0, 3]` for test case 2. Let's correct this explanation for the actual input: Consider the subarray `[0, 3]`, which has a sum of `3`. No deletion needed. If we consider `[-2, 0, 3]` and delete `-2`, we get `[0, 3]` with sum `3`. The largest sum is `3`.
[ "[-1, -2, 0, 3, 1]" ]
Explanation. Consider the subarray `[0, 3, 1]`, which has a sum of `4`. No deletion is needed here. If we consider `[-2, 0, 3, 1]` and delete `-2`, we get `[0, 3, 1]` with sum `4`.
[ "[-2, 5, -1, 3]" ]
Explanation. Consider the subarray `[5, -1, 3]`. If we delete `-1`, the remaining subarray is `[5, 3]` with a sum of `8`.
[ "[-2, -3, -1]" ]
Explanation. The maximum sum is obtained from the subarray `[-1]` with a sum of `-1`. Deleting an element from a longer subarray of negative numbers will not result in a larger sum than simply picking the largest individual element.
Follow-up: Can you solve this problem with O(1) space complexity?
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
- Views
- 2