欢迎使用CSDN-markdown编辑器

来源:互联网 发布:淘宝订单贷款能用多久 编辑:程序博客网 时间:2024/06/10 20:50

求序列的最大连续加权值
线性时间花费O(N)
分治法时间花费O(N*logN)

/*线性*/int maxSubSum4(const vector<int> &a){    int MaxSub = 0; int thisSub = 0;    for (int i = 0; i < a.size(); i++)    {        thisSub += a[i];        if (thisSub > MaxSub)            MaxSub = thisSub;        else if (thisSub < 0)            thisSub = 0;    }    return MaxSub;}/*分治法*/int max3(int maxLeftSum, int maxRightSum, int maxMerge){    return maxLeftSum > maxRightSum ? (maxLeftSum > maxMerge ? maxLeftSum : maxMerge) : (maxRightSum > maxMerge ? maxRightSum : maxMerge);}int maxSumRec(const vector<int> &a, int left, int right){    if (left == right)  // Base case        if (a[left] > 0)            return a[left];        else            return 0;    int center = (left + right) / 2;    int maxLeftSum = maxSumRec(a, left, center);    int maxRightSum = maxSumRec(a, center + 1, right);    int maxLeftBorderSum = 0, leftBorderSum = 0;    for (int i = center; i >= left; i--)    {        leftBorderSum += a[i];        if (leftBorderSum > maxLeftBorderSum)            maxLeftBorderSum = leftBorderSum;    }    int maxRightBorderSum = 0, rightBorderSum = 0;    for (int j = center + 1; j <= right; j++)    {        rightBorderSum += a[j];        if (rightBorderSum > maxRightBorderSum)            maxRightBorderSum = rightBorderSum;    }    return max3(maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum);}int maxSubSum3(const vector<int> &a){    return maxSumRec(a, 0, a.size() - 1);}
0 0