import java.util.Random;
public class MainClass {
public static void main(String[] args) {
int[] array = new int[10];
//生成随机测试数据,数据集里面必须有正有负。
for (int i = 0; i < array.length; i++) {
Random random = new Random();
array[i] = (int) (Math.random() * 10) * (random.nextBoolean() ? 1 : -1);
}
//打印数据集
System.out.println("测试的随机数组:");
for (int n : array) {
System.out.print(n + " ");
}
System.out.println("\n最大子数组和:");
System.out.println(maxSub(array));
}
//最大子数组和的动态规划算法
public static int maxSub(int[] array) {
int retSum = 0;
int sum = 0;
int tempSum = 0;
for (int i = 0; i < array.length; i++) {
if (sum > 0) {
sum = sum + array[i];
if (sum > tempSum) {
tempSum = sum;
}
} else {
sum = array[i];
}
retSum = Math.max(retSum, sum);
}
return retSum;
}
}
测试几轮数据集输出如下: