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
.
Subscribe to see which companies asked this question
动态规划问题:
虽然知道和动态规划相关,但是并没能写正确,和最大连续子数组和还是有很大区别的。
别人的算法:
在连续累乘的过程中,在乘当前值nums[i]时,能够产生最大值的情况为
1). 前面子序列最大正乘积 * 正值(nums[i]为正);
2). 前面子序列最小负乘积 * 负值(nums[i]为负);
那么我们就将前面子序列最大正乘积,以及最小负乘均更新出来,并且易知最大正乘积就是所求,再乘以当前nums[i]
那么前面的子序列最大正乘积是怎么求出来的呢?显然是前一次计算出来的最大正负乘积中的较大者,同时还有一个重新选择最大和最小起点的逻辑,如果之前的最大和最小累乘值同当前元素相乘之后没有当前元素大(或小)那么当前元素就可作为新的起点,因为我们要的是最大,此时不重新选起点将一直为0,例如,前一个元素为0的情况,{1,0,9,2}到9的时候9应该作为一个最大值,也就是新的起点,{1,0,-9,-2}也是同样道理,-9比当前最小值还小,所以更新为当前最小值。
原博主地址,http://blog.csdn.net/nk_test/article/details/48665631
class Solution { public: int maxProduct(vector<int>& nums) { if(nums.empty()) return 0; int maxMul=nums[0]; int minMul=nums[0]; int ans=nums[0]; for(int i=1;i<nums.size();i++) { int a = maxMul*nums[i]; //累乘 int b = minMul*nums[i]; maxMul=max(max(a,b),nums[i]); //更新最大累乘序列,别忘了nums[i],因为 minMul=min(min(a,b),nums[i]); ans=max(ans,maxMul); //更新最大值 } return ans; } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50471620
原作者博客:http://blog.csdn.net/ebowtang