一道简单的算法题,最大子序列之和

366 阅读1分钟

求最大子序列之和问题

题目:求一个列表的子列表之和的最大值

例子:

    const arr = [8, -19, 5, -4, 20];
    // 最大子序列[5, -4, 20], 和为21

思路1:面对这个问题,首先想到的是双层循环把所有的可能性算出来,然后求出结果,这个方法可行,但是时间复杂度O(n^2),显然不能作为一个高质量的算法

思路2:我们引入一个增量的概念,当这个增量对我们的结果有益我们保留下来(增益大于0),反之,将当前循环的数组item赋值给这个增益值(另一个子序列的开始)

公式:

    dp = max(dp + current, current)

leet code上有一张图画的不错

pic
pic

上代码


const array = [8, -19, 5, -4, 20];

const getMaxChildList = function(array: number[]): number {
    let maxSum = array[0];
    let maxContinuousSum = 0;
    for (let i = 0; i < array.length; i++) {
        if (maxContinuousSum > 0) {
            maxContinuousSum = maxContinuousSum + array[i];
        } else {
            maxContinuousSum = array[i];
        }
        maxSum = Math.max(maxContinuousSum, maxSum);
    }
    return maxSum;
};