Maximum Subarray

本文介绍了一种使用动态规划解决最大子数组和问题的方法。通过定义两个状态变量dp[i]和End[i],分别表示包含前i个元素的最大子数组和及以第i个元素结尾的最大子数组和。并给出了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

It's obvious an DP problem.

Let's define:

$dp[i] := $ the maximum sum of subarray in the first $i$ elements.

 

From the base point, the optimal subarray may contain element $A[i]$ or not.

  1. optimal subarray without $A[i]$, so $dp[i] = dp[i-1]$.
  2. optimal subarray ending with $A[i]$.

There're some subtle issues about the second situation. In order to get the second case, we need to know the optimal solution of array ending with $A[i-1]$.

 

So, we have to define another dp table:

$End[i] := $ the maximum sum of subarray ending with $A[i]$.

Obviously, the $End$ array satisfies:

End[i] = max(End[i-1] + A[i], A[i]);

 In fact, we can simplify as

End[i] = (End[i-1] > 0) ? End[i-1] + A[i] : A[i];

 

As both $dp[i]$ and $End[i]$ only relate the previous step, we can use a variable instead of an array to store the result.

end = (end > 0) ? end + A[i] : A[i];
dp = max(dp, end); 

 

Of course, at the initial stage, we consider only one element $A[0]$, thus, we can initialize $dp, end$ as: 

dp = end = A[0];

 


The complete code is:

class Solution {
public:
    int maxSubArray(int A[], int n) {
        int dp = A[0];
        int end = dp;
        
        for(int i = 1; i < n; ++i){
            end = end > 0 ? end + A[i] : A[i];
            dp = dp > end ? dp : end;
        }
        
        return dp;
    }
};

 

转载于:https://www.cnblogs.com/kid551/p/4153428.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值