Java实现最大连续乘积子数组

1 问题描述
给定一个浮点数组,任意取出数组中的若干个连续的数相乘,请找出其中乘积最大的子数组。

2 解决方案
2.1 蛮力法

该方法的时间复杂度为O(n^2)。

package com.liuzhen.practice;

public class Main {
    
    public void getResult(double[] A) {
        double max = 1;
        for(int i = 0;i < A.length;i++) {
            double temp = 1;
            for(int j = i;j < A.length;j++) {
                temp = temp * A[j];
                if(temp > max)
                    max = temp;
            }
        }
        System.out.println(max);
        return;
    }
    
    public static void main(String[] args) {
        Main test = new Main();
        double[] A = {-2.5,4,0,3,0.5,8,-1};
        test.getResult(A);
    }
}

运行结果:

12.0

2.2 动态规划法
该方法的时间复杂度为O(n)。

package com.liuzhen.practice;

public class Main1 {
    
    public void getResult(double[] A) {
        double result = 1;
        double max = 1, min = 1;
        for(int i = 0;i < A.length;i++) {
            max = Math.max(max * A[i], Math.max(min * A[i], A[i]));
            min = Math.min(max * A[i], Math.min(min * A[i], A[i]));
            if(max > result)
                result = max;
        }
        System.out.println(result);
        return;
    }
    
    public static void main(String[] args) {
        Main1 test = new Main1();
        double[] A = {-2.5,4,0,3,0.5,8,-1};
        test.getResult(A);
    }
}

运行结果:

12.0
原文地址:https://www.cnblogs.com/a1439775520/p/12947910.html