(基础)最大子序列

问题:

求一段数列的子序列的和的最大值

输入:

第一排输入数列元素个数n

第二排输入每一个元素

输出:

输出子序列和最大值

输入样例:

6

-2 11 -4 13 -5 -2

输出样例:

20

思想:将数列每个数都加起来,如果该元素+sum大于0,都可能使最后结果最大

#include <stdio.h>
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
const double PI=acos(-1.0);
const int inf=0x7fffffff;
int a[105];
int dp[105];
int n,m,mx,sum; 

int main(){
    int n;
    mx=-inf;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
        mx=max(mx,a[i]);
    }
    if(mx<0) cout<<mx;//如果每一项都小于0,则最大的那个就是最大值 
    else{
        sum=0;
        for(int i=0;i<n;i++){ 
        if(sum+a[i]<0){//如果某个元素使得sum和为0 ,则直接将sum=0,表示不选之前的所有元素,从该数之后开始选 
            sum=0;
        }
        else{
            sum+=a[i];//将数列每个数都加起来,如果该元素+sum大于0,都可能使最后结果最大  
        }
        mx=max(mx,sum);//每次选了数,将当时的最大值保存,循环完就是该数组的子序列最大和 
    }
    }
    cout<<mx;
    return 0; 
}

Yesterday is history, tomorrow is a mystery, but        today is a gift, that is why it's called present  !

猜你喜欢

转载自www.cnblogs.com/xusi/p/12349224.html
今日推荐