最大连续子序列的和

来源:互联网 发布:什么是网络成瘾 编辑:程序博客网 时间:2024/06/09 06:10

代码


#include <stdio.h>int main(){    int cas, i, n;    scanf("%d", &cas);    while (cas--){        scanf("%d", &n);        int a[100] = {0};        for (i = 0; i < n; ++i)            scanf("%d", &a[i]);        int ans = a[0], tot = 0;        for (i = 0; i < n; ++i){            if (tot > 0) tot += a[i];            else tot = a[i];            if (tot > ans) ans = tot;        }        printf("%d\n", ans);    }    return 0;}

说明


由于要让和最大,可以直接屏蔽掉和为负数的情况(tot < 0),但是由于求的是连续子序列的和,不能一遇到负数的项就扔掉。如:5 6 -1 5 4 -7,最大连续子序列和为6+(-1)+5+4=14。

然后用tot更新ans就行了。

原创粉丝点击