最大子序列和

Description

 

给定一个数组a[0,…,n-1],求a的连续子数组的和,使得该子数组的和最大。

Input

 

输入一个整数n,表示数组a的长度为n接下来输入n个整数,分别表示a[n]

Output

 

最大子序列和

Sample Input 1 

8
1
-2
3
10
-4
7
2
-5

Sample Output 1

18

思路:双指针

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std ;

const int N = 100010 ;

int a[N] ;
int n ;

int main(){
    cin >> n ;
    
    for(int i=0;i<n;i++){
        cin >> a[i] ;
    }
    int l = 0,sum = 0,res = 0 ;
    
    while(l<n){
        if(sum+a[l]<0){
            sum = 0 ;
        }else{
            sum = sum + a[l] ;
        }
        l++ ;
        res = max(sum,res) ;
    }
    
    cout << res << endl ;
    
    return 0 ;
}

...

原文地址:https://www.cnblogs.com/gulangyuzzz/p/12368873.html