给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
输入: [2,3,-2,4]
输出: 6
输入: [-2,0,-1]
输出: 0
利用动态规划:
function maxProduct(nums){
let n = nums.length;
let front = 1,
back = 1;
let ans = 0;
for(let i = 0; i < n; i++){
front *= nums[i];
back *= nums[n-1-i];
ans = Math.max(ans,Math.max(front,back));
front = front == 0 ? 1 : front;
back = back == 0 ? 1 : back;
}
return ans;
}
console.log(maxProduct([-2,0,-1]))
还没有评论,来说两句吧...