线性扫描求最长连续子序列 。

扫描法求最长连续子序列。
需要维护两个值,一个当前序列的最大值,一个总的序列的最大值。
当前的序列的最大值为前面的(最大值+当前值)与(当前值)中的较大者。
总的最大值为上一个总最大值与当前最大值中较大者。
例如 45 -88 5 2 -8 -7 88 -9
cur = 45 -43 5 7 -1 -1 88 88
maxs =45 45 45 45 45 45 88 88

int b[100] = {45,-88,5,2,-8,-7,88,-9};
int main(void)
{
    int cur = 0;
    int maxs = -100;

    for(int i = 0; i < 8; i++)
    {
        cur = max(cur+b[i], b[i]);
        maxs = max(cur, maxs);
    }

    cout << maxs << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/canhelove/article/details/84670108