给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。

叁歲伎倆 2024-04-18 09:57 130阅读 0赞

输入: [2,3,-2,4]
输出: 6

输入: [-2,0,-1]
输出: 0

利用动态规划:

  1. function maxProduct(nums){
  2. let n = nums.length;
  3. let front = 1,
  4. back = 1;
  5. let ans = 0;
  6. for(let i = 0; i < n; i++){
  7. front *= nums[i];
  8. back *= nums[n-1-i];
  9. ans = Math.max(ans,Math.max(front,back));
  10. front = front == 0 ? 1 : front;
  11. back = back == 0 ? 1 : back;
  12. }
  13. return ans;
  14. }
  15. console.log(maxProduct([-2,0,-1]))

发表评论

表情:
评论列表 (有 0 条评论,130人围观)

还没有评论,来说两句吧...

相关阅读