JavaScript 中具有最大乘法的子陣列


我們需要編寫一個 JavaScript 函式,該函式以整數陣列(正數和負數)作為第一個且唯一的引數。該函式應該找出乘積最大的子陣列並將其返回。

例如 −

如果輸入陣列是 −

const arr = [4, -5, 2, -3, 1, -4, 0, -3];

那麼輸出應該是 −

const output = 120

因為具有最大乘積的子陣列是 [4, -5, 2, -3]

示例

以下是程式碼 −

const arr = [4, -5, 2, -3, 1, -4, 0, -3];
const maxProduct = (arr = []) => {
   if (arr.length === 0){
      return 0;
   };
   let max = arr[0],
   min = arr[0],
   greatest = arr[0];
   for (let i = 1; i <= arr.length - 1; i++) {
      let tempMax = max * arr[i];
      max = Math.max(
         arr[i],
         Math.max(min * arr[i], max * arr[i])
      );
      min = Math.min(arr[i], Math.min(min * arr[i], tempMax));
      greatest = Math.max(greatest, max);
   }
   return greatest;
};
console.log(maxProduct(arr));

輸出

以下是控制檯輸出 −

120

更新時間: 2021 年 1 月 19 日

105 次檢視

啟動您的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.