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 };
原文地址:https://www.cnblogs.com/xiehongfeng100/p/4571109.html