[leetcode-152-Maximum Product Subarray]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-152-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.

思路:

因为数组里面可能存在负数,那么乘积由i-1时候的最大,如果nums[i]为负数,则到i的时候就变成最小了,于是用两个数组分别记录

到数组i为止的最大值和最小值。

int maxProduct(vector<int>& nums)
{
  int maxpro =nums[0];
  vector<int> proMax(nums.size());
  vector<int> proMin(nums.size());
  proMax[0] = nums[0];
  proMin[0] = nums[0];
  for(int i=1;i<nums.size();i++)
  {
    proMax[i] = max(nums[i],max(proMax[i-1]*nums[i],proMin[i-1]*nums[i]));
    proMin[i] = min(nums[i],min(proMax[i-1]*nums[i],proMin[i-1]*nums[i]));
    maxpro = max(proMax[i],maxpro);
  }
  return maxpro;
}

 

参考:

https://discuss.leetcode.com/topic/3581/share-my-dp-code-that-got-ac

 


以上是关于[leetcode-152-Maximum Product Subarray]的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode152. Maximum Product Subarray

[leetcode-152-Maximum Product Subarray]

leetcode152. Maximum Product Subarray

LeetCode-152-Maximum Product Subarray

[动态规划] leetcode 152 Maximum Product Subarray

leetcode 152. Maximum Product Subarray --------- java