LintCode-乘积最大子序列
找出一个序列中乘积最大的连续子序列(至少包含一个数)。
样例
比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。
分析:访问到每个点的时候,以该点为子序列的末尾的乘积,要么是该点本身,要么是该点乘以以前一点为末尾的序列,注意乘积负负得正,故需要记录前面的最大最小值。
代码:
- class Solution {
- public:
- /**
- * @param nums: a vector of integers
- * @return: an integer
- */
- int maxProduct(vector<int>& nums) {
- // write your code here
- int posMax = nums[0];
- int negMax = nums[0];
- int ret = nums[0];
- for(int i=1;i<nums.size();i++)
- {
- int tempPosMax = posMax;
- int tempNegMax = negMax;
- posMax = max(nums[i],max(nums[i]*tempPosMax,nums[i]*tempNegMax));
- negMax = min(nums[i],min(nums[i]*tempPosMax,nums[i]*tempNegMax));
- ret = max(ret,posMax);
- }
- return ret;
- }
- };
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号