zoukankan      html  css  js  c++  java
  • 算法笔记_133:最大连续乘积子数组(Java)

    目录

    1 问题描述

    2 解决方案

    2.1 蛮力法

    2.2 动态规划法

     


    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

    参考资料:

       1.《编程之法面试和算法心得》  July

  • 相关阅读:
    Java SE(2)
    Java SE(1)
    第二次作业
    Markdown 进阶
    关于主题
    Markdown入门指南
    网络游戏架构与微服务架构简单对比
    微服务框架的存储架构
    轻量级微服务框架的通信架构
    页面静态化
  • 原文地址:https://www.cnblogs.com/liuzhen1995/p/6728744.html
Copyright © 2011-2022 走看看