最大子段和

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1049

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
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

public static void main(String[] args) throws IOException {
int n = Integer.parseInt(in.readLine());
long[] array = new long[n];
int k = 0;
for (int i = 0; i < n; i++) {
array[i] = Long.parseLong(in.readLine());
if (array[i] < 0) {
k++;
}
}
if (k == n) {
out.println(0);
out.flush();
return;
}

// 当前最大子列和以及最大子列和
long currentSum = 0;
long max = array[0];
for (int i = 0; i < n; i++) {
// 如果当前最大子列和是正数,继续加
if (currentSum > 0) {
currentSum += array[i];
} else {
// 负数则丢弃,因为只会让和变小
currentSum = array[i];
}
// 如果当前子列和更大,更新
if (currentSum > max) {
max = currentSum;
}
}
out.println(max);
out.flush();
}
}
Author

Zoctan

Posted on

2018-03-14

Updated on

2023-03-14

Licensed under