乘积最大子序列
题目
找出一个序列中乘积最大的连续子序列(至少包含一个数)。
样例
比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。
题解
对于任意nums[i],以该元素为结束的子序列最大乘积要么是nums[i],要么是nums[i]乘以以nums[i]为结束的子序列的最大乘积。由于负负可以得正,故需要同时记录最大值和最小值。
public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int maxProduct(int[] nums) {
int posMax = nums[0];
int negMin = nums[0];
int max = nums[0];
for (int i=1;i<nums.length;i++)
{
int posMax_tmp = posMax;
int negMin_tmp = negMin;
posMax = Math.max(nums[i],Math.max(nums[i]*posMax_tmp,nums[i]*negMin_tmp));
negMin = Math.min(nums[i],Math.min(nums[i]*posMax_tmp,nums[i]*negMin_tmp));
max = Math.max(posMax,max);
}
return max;
}
}
Last Update 2016.10.28