zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    #256 (Div. 2)A. Rewards
    1113 矩阵快速幂
    1108 距离之和最小V2
    1287 加农炮
    1191 消灭兔子
    1051 最大子矩阵
    1086 背包
    1105 第K大的数
    2016 CCPC 网络赛 B 高斯消元 C 树形dp(待补) G 状压dp+容斥(待补) H 计算几何
    Educational Codeforces Round 18 C dp,思维 D lowbit,思维
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12947910.html
Copyright © 2011-2022 走看看