Fork me on GitHub

[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

 

posted @ 2017-08-08 18:05  hellowOOOrld  阅读(114)  评论(0编辑  收藏  举报