找出有限数列中和值最大的连续子数列

((list) => {
    let max = {
        total: 0,
        first: 0,
        last: 0,
    };
    let tmp = {
        total: 0,
        first: 0,
        last: 0,
    };
    let op = 0;//是否连续,0不连续,1递增连续,-1递减连续
    list.forEach((current, i) => {
        if (i === 0) {
            tmp.total = current;
            max.total = current;
            return;
        }
        const prev = list[i - 1];
        if (op === 0) {
            if (current > prev) {
                op = 1;
            } else if (current < prev) {
                op = -1;
            } else {
                op = 0;
            }
        }
        if (op !== 0 && current - prev === op) {
            tmp.total += current;
        } else {
            if (max.total < tmp.total) {
                max.total = tmp.total;
                max.first = tmp.first;
                max.last = tmp.last;
            }
            op = 0
            tmp.first = i;
            tmp.total = current;
        }
        tmp.last = i;
    });
    if (max.total < tmp.total) {
        max = tmp;
    }
    return [
        "和值:" + max.total,
        "值:" + list[max.first] + "~" + list[max.last],
        "索引:" + max.first + "~" + max.last
    ].join("\n");
})([1, 2, 3, 4, 3, 2, 5, 6, 7, 8]);

发表评论

邮箱地址不会被公开。 必填项已用*标注