acwing 55. 连续子数组的最大和

地址  https://www.acwing.com/problem/content/50/

输入一个 非空 整型数组,数组里的数可能为正,也可能为负。

数组中一个或连续的多个整数组成一个子数组。

求所有子数组的和的最大值。

要求时间复杂度为O(n)。

样例

输入:[1, -2, 3, 10, -4, 7, 2, -5]

输出:18

动态规划的入门样板

 

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

代码

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
       int n = nums.size();
       vector<int> dp(nums.begin(),nums.end());
       int maxnum = dp[0];
        for(int i = 1; i < n ;i++){
            dp[i] = max(dp[i-1]+dp[i],dp[i]);
            if(dp[i]> maxnum)
                maxnum= dp[i];
        }
       
       return maxnum;
    }
};

 

posted on 2019-08-28 17:50  itdef  阅读(144)  评论(0编辑  收藏  举报

导航