51Nod 1049 最大子段和

1049 最大子段和

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注

描述

N个整数组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的连续子段和的最大值。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。

Input

第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N + 1行:N个整数(-10^9 <= A[i] <= 10^9)

Output

输出最大子段和。

Input示例

6
-2
11
-4
13
-5
-2

Output示例

20

题解

动态规划入门题= =…我个大水笔,改个时间补充一下…代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <utility>
#define ll long long

using namespace std ;

int main(){
int n ;
cin >> n ;
ll maxx = 0 ;
ll a[n + 10] ;
for ( int i = 0 ; i < n ; i ++ ){
cin >> a[i] ;
}
ll ans = 0 ;
maxx = ans = a[0] ;
for ( int i = 1 ; i < n ; i ++ ){
maxx = max(maxx , 0LL) + a[i] ;
ans = max(ans , maxx) ;
}
cout << ans << endl ;
return 0 ;
}