Solving Leetcode Interviews in Seconds with AI: Maximum Subarray Sum with One Deletion
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1186" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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
Explanation
Here's the breakdown of the approach, complexities, and the Python code:
- Key Idea: Use dynamic programming to track the maximum subarray sum ending at each index, considering two cases: with deletion and without deletion.
- Handle Deletion: When calculating the maximum sum with deletion, consider deleting the current element or utilizing the maximum sum with deletion from the previous index.
Calculate Overall Max: Maintain a running maximum across all indices and both cases (with and without deletion).
Complexity:
- Runtime: O(n)
- Storage: O(n)
Code
def maximum_subarray_sum(arr):
"""
Finds the maximum sum of a non-empty subarray with at most one deletion.
Args:
arr: A list of integers.
Returns:
The maximum subarray sum.
"""
n = len(arr)
if n == 0:
return 0
# dp_no_deletion[i]: Maximum subarray sum ending at index i without any deletion
dp_no_deletion = [0] * n
# dp_deletion[i]: Maximum subarray sum ending at index i with one deletion
dp_deletion = [0] * n
dp_no_deletion[0] = arr[0]
dp_deletion[0] = 0 # Initial deletion possibility doesn't add value at the beginning.
max_so_far = arr[0]
for i in range(1, n):
# Without deletion: Extend previous subarray or start a new one.
dp_no_deletion[i] = max(arr[i], dp_no_deletion[i - 1] + arr[i])
# With deletion: Delete current element OR use previous deletion and extend the array
dp_deletion[i] = max(dp_no_deletion[i - 1], dp_deletion[i - 1] + arr[i])
max_so_far = max(max_so_far, dp_no_deletion[i], dp_deletion[i])
return max_so_far