找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
例如, 给定序列 [2,3,-2,4]
,
其中乘积最大的子序列为 [2,3]
其乘积为 6
。
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
.
设定当前最大值和最小值,对数组进行循环,对比(
当前数字
×最大值
)
和(当前数字×最小值)分别与当前数值比大小,更新当前最大最小值,如果最大值大于总体最大值则取代之
代码(JavaScript):
/**
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function(nums) {
var max_now;
var min_now;
var max_last=nums[0];
var min_last=nums[0];
var max=nums[0];
for(var i=1;i<nums.length;i++){
max_now=Math.max(Math.max(max_last*nums[i],min_last*nums[i]),nums[i]);
min_now=Math.min(Math.min(max_last*nums[i],min_last*nums[i]),nums[i]);
max_last=max_now;
min_last=min_now;
max=Math.max(max_now,max);
}
return max;
};