zoukankan      html  css  js  c++  java
  • LeetCode之“动态规划”:Maximum Product Subarray

      题目链接

      题目要求:

      Find the contiguous subarray within an array (containing at least one number) which has the largest product.

      For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.

      题目分析参考自一博文

      这道题跟Maximum Subarray模型上和思路上都比较类似,还是用一维动态规划中的“局部最优和全局最优法”。这里的区别是维护一个局部最优不足以求得后面的全局最优,这是由于乘法的性质不像加法那样,累加结果只要是正的一定是递增,乘法中有可能现在看起来小的一个负数,后面跟另一个负数相乘就会得到最大的乘积。不过事实上也没有麻烦很多,我们只需要在维护一个局部最大的同时,再维护一个局部最小,这样如果下一个元素遇到负数时,就有可能与这个最小相乘得到当前最大的乘积和,这也是利用乘法的性质得到的。

     1 class Solution {
     2 public:
     3     int maxThree(int a, int b, int c)
     4     {
     5         int tmp = (a > b) ? a : b;
     6         return (tmp > c) ? tmp : c;
     7     }
     8     
     9     int maxProduct(vector<int>& nums) {
    10         int sz = nums.size();
    11         if(sz == 0)
    12             return 0;
    13 
    14         int max_local = nums[0];
    15         int min_local = nums[0];
    16         int global = nums[0];
    17         for(int i = 1; i < sz; i++)
    18         {
    19             int max_copy = max_local;
    20             max_local = max(max(max_local * nums[i], nums[i]), min_local * nums[i]);
    21             min_local = min(min(min_local * nums[i], nums[i]), max_copy * nums[i]);
    22             global = max(global, max_local);
    23         }
    24         
    25         return global;
    26     }
    27 };
  • 相关阅读:
    [HAOI2008]硬币购物
    [NOI2006]网络收费
    [HNOI2014]米特运输
    Codeforces Round #536 (Div. 2)
    [洛谷P3931]SAC E#1
    [洛谷P1402]酒店之王
    [洛谷P4174][NOI2006]最大获利
    [CF1082G]Petya and Graph
    [CF1095F]Make It Connected
    [CF1083B]The Fair Nut and Strings
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4571109.html
Copyright © 2011-2022 走看看