首页 > 代码库 > 152. Maximum Product Subarray (Array; DP)

152. Maximum Product Subarray (Array; DP)

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,不同的是

  • max(max_local*nums[i], nums[i])表示:如果之前的数max_local和nums[i]符号相反,那么nums[i]会是max
  • max(max(max_local*nums[i], nums[i]), min_local*nums[i])表示:如果nums[i]是个负数,那么就可能和min_local组成局部最优=>这是为什么我们要设置min_local
class Solution {
public:
    int maxProduct(vector<int>& nums) {
         int max_local = nums[0];
         int min_local = nums[0];
         int max_copy;
         int global = nums[0];
         
         for(int i = 1; i < nums.size(); i++){
              max_copy = max_local;
              max_local = max(max(max_local*nums[i], nums[i]), min_local*nums[i]);
              min_local = min(min(max_copy*nums[i], nums[i]), min_local*nums[i]);
              global = max(global,max_local);
         }
         
         return global;
    }
};

 

152. Maximum Product Subarray (Array; DP)