【C/C++】子数组的最大累加和问题

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    /**
     * max sum of the subarray
     * @param arr int整型vector the array
     * @return int整型
     */
    int maxsumofSubarray(vector<int>& arr) {
        // write code here
        int n = arr.size();
        vector <int> dp;
        dp.insert(dp.begin(), n, 0);
        int maxx = 0;
        dp[0] = arr[0];
        for (int i = 1; i < n; i++)
        {
            dp[i] = max(arr[i], (dp[i-1] + arr[i]));
            maxx = max(maxx, dp[i]);
        }
        return maxx;
    }
};

int main()
{
    vector<int> arr {1, -2, 3, 5, -2, 6, -1};
    Solution solution;
    cout << solution.maxsumofSubarray(arr) << endl;
    system("pause");
} 
原文地址:https://www.cnblogs.com/kinologic/p/14669838.html