zoukankan      html  css  js  c++  java
  • 子数组最大乘积

    给定一个double类型的数组arr,当中的元素可正可负可0,返回子数组累乘的最大乘积。比如arr=[-2.5,4,0,3,0.5。8。-1]。子数组[3,0.5,8]累乘能够获得最大的乘积12,所以返回12。

    解析:此题能够运用动态规划解决

    设f[i]表示以i为结尾的最大值,g[i]表示以i结尾的最小值,那么

    f[i+1] = max{f[i]*arr[i+1], g[i]*arr[i+1],arr[i+1]} ,仅仅有这三种情况。

    考虑到f[i],g[i]仅仅和i-1有关。那么能够用局部变量就可以搞定,而不用使用数组。

    C++风格代码:

    class Solution {
        public:
            double maxProduct(vector<double> arr) 
            {
                if(arr.size() == 0)
                    return 0;
                double minVal = arr[0];
                double maxVal = arr[0];
                double rtn = arr[0];
     
                double tmpMax = 0;
                double tmpMin = 0;
     
                for(int i = 1; i < arr.size(); i++)
                {  
                    //cout << "max	" << maxVal << endl;
                    //cout << "min	" << minVal << endl;
                    tmpMax = max(maxVal * arr[i], minVal * arr[i]);
                    tmpMin = min(maxVal * arr[i], minVal * arr[i]);
     
                    maxVal = max(tmpMax, arr[i]);
                    minVal = min(tmpMin, arr[i]);
     
                    rtn = max(rtn, maxVal);
                }  
                return rtn;
            }  
    };
    或者还有一种C代码:

    // 子数组的最大乘积
    int MaxProduct(int *a, int n)
    {
        int maxProduct = 1; // max positive product at current position
        int minProduct = 1; // min negative product at current position
        int r = 1; // result, max multiplication totally
    
        for (int i = 0; i < n; i++)
        {
            if (a[i] > 0)
            {
                maxProduct *= a[i];
                minProduct = min(minProduct * a[i], 1);
            }
            else if (a[i] == 0)
            {
                maxProduct = 1;
                minProduct = 1;
            }
            else // a[i] < 0
            {
                int temp = maxProduct;
                maxProduct = max(minProduct * a[i], 1);
                minProduct = temp * a[i];
            }
    
            r = max(r, maxProduct);
        }
    
        return r;
    }






  • 相关阅读:
    Git fetch和git pull的区别
    gitlab数据迁移
    阿里云CentOS7挂载SSD云盘的方法
    phpQuery的用法
    用shell查找某目录下的最大文件
    gearman 简介
    学习笔记(3)——实验室集群WMS服务配置
    学习笔记(2)——实验室集群LVS配置
    Fedora16的双显卡切换问题
    学习笔记(1)——实验室集群配置
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5362317.html
Copyright © 2011-2022 走看看