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
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.
Solution
func maximumSum(arr []int) int {
n := len(arr)
maxright := make([]int,n)
maxleft := make([]int,n)
maxright[0] = arr[0]
maxleft[n-1] = arr[n-1]
ret := arr[0]
for i:=1;i<n;i++{
maxright[i] = max(arr[i], maxright[i-1]+arr[i])
j := n-1-i
maxleft[j] = max(arr[j], maxleft[j+1]+arr[j])
ret = max(ret, maxright[i])
}
for i:=1;i<n-1;i++{
ret = max(ret, maxright[i-1]+maxleft[i+1])
}
return ret
}
func max(a, b int)int{
if a>b{
return a
}
return b
}

本文探讨了给定整数数组中,删除至多一个元素后,非空连续子数组的最大和问题。通过动态规划方法,计算从左到右和从右到左的最大子数组和,并考虑删除元素的影响,最终找到全局最大值。
1643

被折叠的 条评论
为什么被折叠?



