[LeetCode]Maximum Subarray Sum with One Deletion@Golang

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值