1007. Maximum Subsequence Sum (25)

题目url:http://pat.zju.edu.cn/contests/pat-a-practise/1007

reference url:http://blog.csdn.net/xtzmm1215/article/details/39010843

/*经典DP问题, 基于这样一个事实:保存一个最大字段和以及一个当前子段和, 

如果当前字段和大于当前最大字段和, 那么更新这个最大字段和,

如果当前字段和为负数的时候, 直接把当前字段和甚设置成0, */



#include <cstdio>

#include <stdio.h>

int a[10001];

int main(){

    int k;

    scanf("%d", &k);

    for (int i = 0; i < k; i++){

        scanf("%d", &a[i]);

    }

    int sum = 0, start = 0, end = k - 1, temp = 0, tempi = 0, tempj = 0;

    for (int i = 0; i < k; i++){

        if (temp >= 0){

            temp += a[i];

            tempj = i;

        }

        else{

            temp = a[i];

            tempi = i;

            tempj = i;

        }

        if (temp > sum || (temp == 0 && end == k -1)){

            sum = temp;

            start = tempi;

            end = tempj;

        }

    }

    printf("%d %d %d\n", sum, a[start], a[end]);

    return 0;

}
the time complexity is O(n)

你可能感兴趣的:(sequence)