JavaScript 中任意兩個相鄰元素的最大乘積


問題

我們需要編寫一個 JavaScript 函式,它接受一個數字陣列。

我們的函式應找到在陣列中乘以 2 個相鄰數字所獲得的最大乘積。

範例

以下為程式碼 −

 演示

const arr = [9, 5, 10, 2, 24, -1, -48];
function adjacentElementsProduct(array) {
   let maxProduct = array[0] * array[1];
   for (let i = 1; i < array.length; i++) {
      product = array[i] * array[i + 1];
      if (product > maxProduct)
         maxProduct = product;
   }
   return maxProduct;
};
console.log(adjacentElementsProduct(arr));

輸出

50

更新時間:17-Apr-2021

598 瀏覽

開始你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.