pat 1007. Maximum Subsequence Sum (25)

//数据
10
-10 1 2 3 4 -5 -23 3 7 -21
5
0 0 0 0 0
5
1 2 -3 0 2
5
1 2 0 -3 2
5     //容易被忽略的数据
-1 -2 -3 0 -4
5
-1 -2 -3 -4 -5

//求最大字段和 并输出最大子段的始 终元素
//时间复杂度为O(N)
//下面这段代码是核心
//从i=0时开始遍历,若找到更大的子段和则更新当前最大字段和及最大子段和的始 终元素
//若当前子段和为0,则从下一个元素开始从新遍历(重点)
///即:序列和为0的序列ai---aj中,没有以ak(i

 for(i=0; i         sumsub+=variable[i];
        if(sumsub>maxsub) {
            maxsub=sumsub;
            subend=i;
            subbegin=temp;
        } else if(sumsub<0) {
            sumsub=0;
            temp=i+1;
        }
    }
//Code:
#include
#include
#include
#include
#include
using namespace std;
const int maxn=10003;
int variable[maxn];
int n;
int subbegin,subend;
int maxsub,sumsub;

void subMaxSum() {
    int i;
    maxsub=-1;
    sumsub=0;
    subbegin=0;
    int temp=0;
    subend=0;
    for(i=0; i         sumsub+=variable[i];
        if(sumsub>maxsub) {
            maxsub=sumsub;
            subend=i;
            subbegin=temp;
        } else if(sumsub<0) {
            sumsub=0;
            temp=i+1;
        }
    }
    printf("%d %d %d\n",maxsub,variable[subbegin],variable[subend]);
}

int main() {
    int i,j;
    while(cin>>n) {
        bool flag=false;
        for(i=0; i             cin>>variable[i];
            if(variable[i]>=0)
                flag=true;
        }
        if(flag==false) {
            printf("0 %d %d\n",variable[0],variable[n-1]);
        } else
            subMaxSum();
    }
    return 0;
}





你可能感兴趣的:(pat)