Leetcode 1186: Maximum Subarray Sum with One Deletion

grid47
grid47
Exploring patterns and algorithms
Jul 11, 2024 6 min read

Given an array of integers, determine the maximum sum of a non-empty contiguous subarray where you are allowed to optionally delete at most one element. The subarray must remain non-empty after any deletion.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array representing the values of elements.
Example: Input: arr = [2, -4, 3, 7]
Constraints:
• 1 <= arr.length <= 10^5
• -10^4 <= arr[i] <= 10^4
Output: The output is a single integer representing the maximum sum of the subarray with at most one optional deletion.
Example: Output: 9
Constraints:
• The subarray must remain non-empty.
Goal: To calculate the maximum sum of a contiguous subarray with the option to delete one element.
Steps:
• Use dynamic programming to calculate forward maximum sums.
• Compute backward maximum sums for the array.
• Combine results to evaluate maximum sums with one deletion allowed.
Goal: The solution must handle large arrays efficiently.
Steps:
• Time complexity should be O(n).
• Space complexity should be O(n) or optimized further.
Assumptions:
• The input array always contains at least one element.
• Subarray sums may be negative.
Input: Input: arr = [3, -1, 5, -2]
Explanation: You can choose [3, -1, 5] and optionally remove -1 to maximize the sum to 8.

Input: Input: arr = [-3, -1, -4]
Explanation: Since all elements are negative, the best subarray is [-1] for a maximum sum of -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus