给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n 例如,当(a[1],a[2],a[3],a[4],a[5],a[6])}=(-2,11,-4,13,-5,-2)时,最大子段和为20。
最大子段和是动态规划中的一种。
import java.util.Random;
import java.util.Scanner;
public class maxSum {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Random rd = new Random();
System.out.println("请输入数据规模n(10的倍数):");
int n = scan.nextInt();
int[] a = new int[n];
for(int i=0; isum){
sum = thissum;
}
}
}
return sum;
}
//优化后的暴力法 (O(n^2))
public int maxSumBF(int a[]){
int n = a.length - 1;
int sum = 0;
for(int i=1; i<=n; i++){
int thissum = 0;
for(int j=i; j<=n; j++){
thissum += a[j];
if(thissum>sum){
sum = thissum;
}
}
}
return sum;
}
//分治算法(n log(n))
private static int maxSubSum(int a[], int left, int right){
int sum = 0;
if(left == right){
sum = a[left]>0?a[left]:0;
}else{
int center = (left + right)/2;
int leftsum = maxSubSum(a,left,center);
int rightsum = maxSubSum(a,center+1,right);
int s1 = 0;
int lefts = 0;
for(int i=center; i>=left; i--){
lefts += a[i];
if(lefts>s1){
s1 = lefts;
}
}
int s2 = 0;
int rights = 0;
for(int i=center+1; i<=right; i++){
rights += a[i];
if(rights>s2){
s2 = rights;
}
}
sum = s1 + s2;
f(sum0){
b += a[i];
}else{
b = a[i];
}
if(b>sum){
sum = b;
}
}
return sum;
}
}