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
    
  • 相关阅读:
    FastCgi与PHPfpm之间的关系
    PHP中多线程处理
    EASYUI+MVC4通用权限管理平台前言
    常用企业建站源码
    Oracle数据库同步服务
    Jquery easyui +MVC4 管理信息系统
    《自动化技术中的进给电气传动》1.1节和1.2节读书笔记
    FTP
    Samba
    rsync
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13077788.html
Copyright © 2011-2022 走看看