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.

  • 相关阅读:
    PHP读写XML文件的四种方法
    如何在linux系统中设置静态ip地址
    Memcached和Memcache安装(64位win7)
    Mysql存储过程和函数区别介绍
    随笔
    Vue 中使用axios传参数,后端收不到数据
    vs2019创建mvc连接mysql
    dapper多表查询
    Java并发编程:volatile关键字解析
    Mysql Innodb 间隙锁浅析
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4171283.html
Copyright © 2011-2022 走看看