LintCode "Continuous Subarray Sum"

A variation to a classical DP: LCS.

class Solution {
public:
    /**
    * @param A an integer array
    * @return  A list of integers includes the index of
    *          the first number and the index of the last number
    */
    vector<int> continuousSubarraySum(vector<int>& A) {
        vector<int> ret;

        size_t len = A.size();

        int curr = A[0];
        int sum = A[0], csum = A[0];
        int s = 0, e = 0, ss = 0, ee = 0;
        for (int i = 1; i < len; i++)
        {
            int nsum = csum + A[i];
            if (A[i] > nsum)
            {
                ss = ee = i;
                csum = A[i];
            }
            else
            {
                ee = i;
                csum = nsum;
            }
    
            if(csum > sum) // update global record
            {
                sum = nsum;
                s = ss;
                e = ee;
            }
        }

        ret.push_back(s);
        ret.push_back(e);
        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4768821.html