在线处理
每输入一个数据就进行在线的处理
发现更大的和那么更新MAX
小的和丢弃
在任何情况下都能给出最优的解
import java.util.Scanner;
public class code02 {
public static int MaxSubseqSum(int[] arr, int N) {
int ThisSum, MaxSum;
ThisSum = MaxSum = 0;
for (int i = 0; i < N; i++) {
ThisSum += arr[i];
if (ThisSum > MaxSum) {
MaxSum = ThisSum;
} else if (ThisSum < 0) {
ThisSum = 0;
}
}
return MaxSum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int MAX = MaxSubseqSum(arr, N);
System.out.println(MAX);
}
}