最大子段和(java)
题目描述:
若给定n个整数组成的序列a1,a2,a3,……an,求该序列形如ai+a(i+1)+……+aj的最大值。
思路:
辅助数组b[j]用来记录一j为尾的子段和集合中的最大子段和,a[i]为序列的第i个元素。
那么当b[i-1]>0时,b[i]=b[i-1]+a[i],否则 b[i]=a[i];
import java.util.Scanner;
public class 最大子段和 {
static int maxn = 50005;
static long a[] = new long[maxn];
static long b[] = new long[maxn];
public static long MIS(int n, long a[], long b[], long max) {
for (int i = 0; i < n; i++) {
if (i == 0) {
b[i] = a[i];
max = b[i];
} else {
if (b[i - 1] <= 0)
b[i] = a[i];
else
b[i] = b[i - 1] + a[i];
if (b[i] > max)
max = b[i];
}
}
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
long max = 0;
max = MIS(n, a, b, max);
System.out.println(max);
}
}