LINTCODE——最大子数组III

LINTCODE——最大子数组III

思路:动态规划的方法,记mustTheLast[i][j]为在前i个数中分成j段,且第j段必须有第i个数的最大值,notTheLast[i][j]为前i个中分成j段,且第j段不一定含有第i个数的最大值;注意初始化的数据,不能全部初始化为0,不然在全部为负整数以及一些其他情况的数组会出错;
动态规划方程为:
mustTheLast[i][j] = max(mustTheLast[i-1][j] + nums[i-1] ,notTheLast[i-1][j-1] + nums[i-1]);
notTheLast[i][j] = max(notTheLast[i-1][j] ,mustTheLast[i][j]);

class Solution {
public:
    /*
     * @param nums: A list of integers
     * @param k: An integer denote to find k non-overlapping subarrays
     * @return: An integer denote the sum of max k non-overlapping subarrays
     */
    int maxSubArray(vector<int> &nums, int k) {
        // write your code here
        int n = nums.size();
        if(k > n)
            return INT_MIN;
        vector<vector<int> > notTheLast(n+1,vector<int>(k+1,-10000));
        vector<vector<int> > mustTheLast(n+1,vector<int>(k+1,-10000));
        mustTheLast[0][0] = 0;  
        notTheLast[0][0] = 0 ; 
        for(int i = 1 ; i <= n; i++)
        {
            mustTheLast[i][0] = 0 ; 
            notTheLast[i][0] = 0;  

            for(int j = 1 ; j <= k; j++)
            {
                mustTheLast[i][j] = max(mustTheLast[i-1][j] + nums[i-1] ,notTheLast[i-1][j-1] + nums[i-1]);

                notTheLast[i][j] = max(notTheLast[i-1][j] ,mustTheLast[i][j]);

            }

        }
        return notTheLast[n][k];

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值