《程序员代码面试指南》第八章 数组和矩阵问题 数组中子数组的最大累乘积

题目

数组中子数组的最大累乘积

java代码

package com.lizhouwei.chapter8;

/**
 * @Description: 数组中子数组的最大累乘积
 * @Author: lizhouwei
 * @CreateDate: 2018/5/8 21:59
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_19 {
    public double maxProduct(double[] arr) {
        double maxValue = arr[0];
        double minValue = arr[0];
        double curMinValue = arr[0];
        double curMaxValue = arr[0];
        double res = arr[0];
        for (int i = 1; i < arr.length; i++) {
            curMaxValue = maxValue * arr[i];
            curMinValue = minValue * arr[i];
            maxValue = Math.max(Math.max(curMinValue, curMaxValue), arr[i]);
            minValue = Math.min(Math.min(curMinValue, curMaxValue), arr[i]);
            res = Math.max(res, maxValue);
        }
        return res;
    }

    //测试
    public static void main(String[] args) {
        Chapter8_19 chapter = new Chapter8_19();
        double[] arr = {-2.5, 4, 0, 3, 0.5, 8, -1};
        System.out.print("数组 arr = {-2.5, 4, 0, 3, 0.5, 8, -1}最大累积为:");
        double res = chapter.maxProduct(arr);
        System.out.print(res);
    }
}

结果

posted @ 2018-05-08 22:11  lizhouwei  阅读(105)  评论(0编辑  收藏  举报