zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】动态规划与贪婪法题5:Maximum Product Subarray

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    Maximum Product Subarray

    Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
    Example 1:
    Input: [2,3,-2,4]
    Output: 6
    Explanation: [2,3] has the largest product 6.
    Example 2:
    Input: [-2,0,-1]
    Output: 0
    Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

    C++
     
    /*
    问题:求最大子数组乘积
    方法:动态规划
    两个dp数组,其中f[i]和g[i]分别表示包含nums[i](以nums[i]结尾)时的最大和最小子数组乘积,
    初始化时f[0]和g[0]都初始化为nums[0],其余都初始化为0。
     
    从数组的第二个数字开始遍历,此时的最大值和最小值只会在这三个数字之间产生,
    即f[i-1]*nums[i],g[i-1]*nums[i],和nums[i]。
    所以我们用三者中的最大值来更新f[i],用最小值来更新g[i],然后用f[i]来更新结果res即可
    */
    class Solution
    {
    public:
        int maxProduct(vector<int>& nums)
        {
            if(nums.empty()) return 0;
               
            int res = nums[0], n = nums.size();
            vector<int> f(n), g(n); //分配空间,初始化
            f[0] = nums[0];
            g[0] = nums[0];
           
            for (int i = 1; i < n; i++) //从a[1]开始遍历
            {
                f[i] = max(max(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i]); //最大数更新
                g[i] = min(min(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i]); //最小数更新
                res = max(res, f[i]); //结果更新
            }
            return res;
        }
    };
     
    /*
    空间优化,用两个变量代替数组dp 
    */
    class Solution
    {
    public:
        int maxProduct(vector<int>& nums)
        {
            if (nums.empty()) return 0;
            int res = nums[0], mn = nums[0], mx = nums[0];
            for (int i = 1; i < nums.size(); ++i)
            {
                int tmax = mx, tmin = mn;//上一次的最小值和最大值
                mx = max(max(nums[i], tmax * nums[i]), tmin * nums[i]);
                mn = min(min(nums[i], tmax * nums[i]), tmin * nums[i]);
                res = max(res, mx);
            }
            return res;
        }
    };
     
  • 相关阅读:
    【动画】看动画轻松理解「Trie树」
    浅析HTTP/2的多路复用
    HTTPS 详解
    PHP写时复制(Copy On Write)
    golang 几种字符串的拼接方式
    正排索引和倒排索引简单介绍
    传值还是传引用
    lvs与nginx区别
    Docker运行操作系统环境(BusyBox&Alpine&Debian/Ubuntu&CentOS/Fedora)
    原创-thanos组件(聚合多个prometheus组件)原理介绍
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10229085.html
Copyright © 2011-2022 走看看