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.
題目:返回?cái)?shù)組中連續(xù)的最大值。
思路:用一維動(dòng)態(tài)規(guī)劃中的“局部最優(yōu)和全局最優(yōu)法”助泽。利用乘法性質(zhì):累加結(jié)果只要是正的一定是遞增蛾默,乘法中有可能現(xiàn)在看起來(lái)小的一個(gè)負(fù)數(shù)窘拯,后面跟另一個(gè)負(fù)數(shù)相乘就會(huì)得到最大的乘積肄梨。所以身坐,只需要在維護(hù)一個(gè)局部最大的同時(shí)域携,在維護(hù)一個(gè)局部最小帆啃,這樣如果下一個(gè)元素遇到負(fù)數(shù)時(shí)溯泣,就有可能與這個(gè)最小相乘得到當(dāng)前最大的乘積和。
/**
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function(nums) {
var i , j;
var len = nums.length;
var max = 0;
var min = 0;
var result = 0;
var temp_max = 0;
if(nums.length==0) return 0;
else if(nums.length==1) return Number(nums);
max = nums[0];
min = nums[0];
result = nums[0];
for(i=1;i<nums.length;i++)
{
temp_max = max;
max = Math.max(Math.max(nums[i]*max,nums[i]),nums[i]*min);
min = Math.min(Math.min(nums[i]*temp_max,nums[i]),nums[i]*min);
result = Math.max(result,max);
}
return result;
};