最大连续子序列和

210 阅读1分钟
    • 题目描述:
    • 给出一个整数序列S,其中有N个数,定义其中一个非空连续子序列T中所有数的和为T的“序列和”。
      对于S的所有非空连续子序列T,求最大的序列和。
      变量条件:N为正整数,N≤1000000,结果序列和在范围(-2^63,2^63-1)以内。
    • 输入:
    • 第一行为一个正整数N,第二行为N个整数,表示序列中的数。
    • 输出:
    • 输入可能包括多组数据,对于每一组输入数据,
      仅输出一个数,表示最大序列和。\
    • 样例输入:
    • 5
      1 5 -3 2 4
      
      6
      1 -2 3 4 -10 6
      
      4
      -3 -1 -2 -5
      
    • 样例输出:
    • 9
      7
      -1
      
    • 来源:

    • 2006年清华大学计算机研究生机试真题

    • #define _CRT_SECURE_NO_WARNINGS
      #include <iostream>
      #include <cstdio>
      #include <cmath>
      #include <cstdlib>
      #include <cstring>
      #include <climits>
      #include <stack>
      #include <queue>
      #include <vector>
      #include <string>
      #include <map>
      #include <set>
      #include <algorithm>
      using namespace std;
      const int maxn = 1e6 + 7;
      long long myInts[maxn];
      long long maxSubSum(long long aryInt[], int n) {
      	long long sum = LLONG_MIN, tmp = 0;
      	for (int i = 0; i < n; ++i) {
      		if (tmp > 0)
      			tmp += aryInt[i];
      		else tmp = aryInt[i];
      		sum = max(sum, tmp);
      	}
      	return sum;
      }
      int main() {
      	int n;
      	while (~scanf("%d", &n)) {
      		for (int i = 0; i < n; ++i)
      			scanf("%lld", myInts + i);
      		printf("%lld\n", maxSubSum(myInts, n));
      	}//在九度OJ上提交,%64d输出WA,%lld就AC
      
      	return 0;
      }
      
    • \

    • zzuwenjie 2017-3-30 22:18:14

    • \