美文网首页
152. Maximum Product Subarray

152. Maximum Product Subarray

作者: 菁卡因 | 来源:发表于2016-12-01 17:38 被阅读0次

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.
题目:返回数组中连续的最大值。
思路:用一维动态规划中的“局部最优和全局最优法”。利用乘法性质:累加结果只要是正的一定是递增,乘法中有可能现在看起来小的一个负数,后面跟另一个负数相乘就会得到最大的乘积。所以,只需要在维护一个局部最大的同时,在维护一个局部最小,这样如果下一个元素遇到负数时,就有可能与这个最小相乘得到当前最大的乘积和。

 /**
 * @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;
       };

相关文章

网友评论

      本文标题:152. Maximum Product Subarray

      本文链接:https://www.haomeiwen.com/subject/wvaxmttx.html