【算法】最大子数组和的动态规划算法,Java实现

x33g5p2x  于2021-11-11 转载在 Java  
字(0.7k)|赞(0)|评价(0)|浏览(359)
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;
    }
}

测试几轮数据集输出如下:

相关文章