152. Maximum Product Subarray

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;
       };
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容