zoukankan      html  css  js  c++  java
  • leetcode Maximum Product Subarray

    之前好像做过这样的,以前是加法,现在是乘法。

    一开始我也傻逼得用n方的试了下,肯定是TLE的。

    那显然就是可以O(n)解决了

    用两个dp数组,一个存最大值,一个存最小值,因为可能是负数再乘以负数就很大了,所以每次更新需要借助最小值一同更新最大值。最后遍历一边dp大的数组就有答案了。

    class Solution {
    public:
        int maxProduct(int A[], int n)
        {
            int dp[n], dpNeg[n], maximum;
            memset(dp, 0, sizeof(dp));
            memset(dpNeg, 0, sizeof(dpNeg));
            dp[0] = A[0]; dpNeg[0] = A[0];
            for (int i = 1; i < n; i++)
            {
                dp[i] = max(dp[i - 1] * A[i], A[i]);
                dp[i] = max(dpNeg[i - 1] * A[i], dp[i]);
                dpNeg[i] = min(dpNeg[i - 1] * A[i], A[i]);
                dpNeg[i] = min(dp[i - 1] * A[i], dpNeg[i]);
            }
            for (int i = 0; i < n; i++)
            {
                if (dp[i] > maximum)
                    maximum = dp[i];
            }
            return maximum;
        }
    };

    这题也unlock了

    也可以看看Ganker的,他是在for里面就判断了maximum了。说是全局最优和局部最优的最大值。其实思路一样的吧。

    同时附上leetcode上的解题思路:

    Maximum Product Subarray

    Besides keeping track of the largest product, we also need to keep track of the smallest product. Why? The smallest product, which is the largest in the negative sense could become the maximum when being multiplied by a negative number.

    Let us denote that:

    f(k) = Largest product subarray, from index 0 up to k.
    

    Similarly,

    g(k) = Smallest product subarray, from index 0 up to k.

    Then,

    f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] )
    g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] )
    

    There we have a dynamic programming formula. Using two arrays of size n, we could deduce the final answer as f(n-1). Since we only need to access its previous elements at each step, two variables are sufficient.

  • 相关阅读:
    Android SDK 国内镜像及配置方法
    Python多线程学习
    JProfiler 8下载地址和注册码
    Python自动化测试工具Splinter简介和使用实例
    linux系统新建用户ssh远程登陆显示-bash-4.1$解决方法
    Linux系统安装VMware Tools
    CentOS minimal网络设置
    接口测试之webservice
    VirtualBox-Linux系统安装增强功能
    PhantomJS快速入门
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4171283.html
Copyright © 2011-2022 走看看