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
    
  • 相关阅读:
    css学习笔记1
    HTML学习笔记4
    Layui使用入门教程
    MVC _Layout
    C# MVC _viewstart.cshtml的作用
    用javascript提交表单
    form表单中的属性和标签
    <input>标签中id和name的作用和区别
    input type = button 的onclick属性调用函数
    form表单提交onclick和onsubmit
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12947910.html
Copyright © 2011-2022 走看看