152. Maximum Product Subarray

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Input: [2,-5,-2,-4,3]
Output: 24
Explanation: [-2,-4,3] has the largest product 24.

  

问题:

  求给定数组中连续元素子数组的乘积最大。

方法:

动态规划:

最优解 = max ( 上一个最大值 , 本次最大值 )

而,本次最大值 = max ( 上一个最大值 * 该当值,该当值 )

注意:由于乘法的特殊性,负负得正,要求最大值则:

该当值如果为负数,则*上一个值的最小值

反之,该当值为正数,则*上一个的最大值

参考代码:

 1 class Solution {
 2 public:
 3     int maxProduct(vector<int>& nums) {
 4         int rmax, rmin, res;
 5         if(nums.empty()) return 0;
 6         rmax=nums[0];
 7         rmin=nums[0];
 8         res=nums[0];
 9         for(int i=1; i<nums.size(); i++){
10             if(nums[i]<0) swap(rmax,rmin);
11             rmin = min(nums[i], rmin*nums[i]);
12             rmax = max(nums[i], rmax*nums[i]);
13             res=max(res,rmax);
14         }
15         return res;
16     }
17 };
原文地址:https://www.cnblogs.com/habibah-chang/p/12433364.html