LeetCode 1186 Maximum Subarray Sum with One Deletion (dp)

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

题目链接:https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/

题目大意:至多删一个最大连续和

题目分析:dp[i][0/1](0表示未删,1表示已删)代表到i时,若不删i则必须选i的最大连续和,转移方程很显然

class Solution {
    public int maximumSum(int[] arr) {
        int n = arr.length;
        if (n == 1) {
            return arr[0];
        }
        int[][] dp = new int[n][2];
        dp[0][1] = 0;
        dp[0][0] = arr[0];
        int res = Integer.MIN_VALUE;
        for (int i = 1; i < n; i++) {
            dp[i][0] = Math.max(dp[i - 1][0] + arr[i], arr[i]);
            dp[i][1] = Math.max(dp[i - 1][0], dp[i - 1][1] + arr[i]);
            res = Math.max(res, Math.max(dp[i][0], dp[i][1]));
        }
        return res;
    }
}

由于第i位只和i-1有关,故可通过变量替换省去数组

class Solution {
    public int maximumSum(int[] arr) {
        int preD = 0, pre = arr[0], cur = 0, curD = 0;
        int res = arr[0];
        for (int i = 1; i < arr.length; i++) {
            cur = Math.max(pre + arr[i], arr[i]);
            curD = Math.max(pre, preD + arr[i]);
            res = Math.max(res, Math.max(cur, curD));
            pre = cur;
            preD = curD;
        }
        return res;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值