JavaScript 中連續子陣列的最大和


我們需要編寫一個 JavaScript 函式,該函式接收一個包含正整數和負整數陣列的陣列。由於陣列還包含負元素,連續元素的總和可能為負或正。

我們的函式應從陣列中選取一個連續元素的陣列,使總和最大。最後,函式應返回該陣列。

例如 -

如果輸入陣列是 -

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

那麼最大的可能和為 7,輸出子陣列應為 -

const output = [4, -1, -2, 1, 5];

示例

以下是程式碼 -

const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
const maximumSubarray = (arr = []) => {
   let max = -Infinity;
   let currentSum = 0;
   let maxStartIndex = 0;
   let maxEndIndex = arr.length - 1;
   let currentStartIndex = 0;
   arr.forEach((currentNumber, currentIndex) => {
      currentSum += currentNumber;
      if (max < currentSum) {
         max = currentSum;
         maxStartIndex = currentStartIndex;
         maxEndIndex = currentIndex;
      }
      if (currentSum < 0) {
         currentSum = 0;
         currentStartIndex = currentIndex + 1;
      }
   });
   return arr.slice(maxStartIndex, maxEndIndex + 1);
};
console.log(maximumSubarray(arr));

輸出

以下是控制檯上的輸出 -

[ 4, -1, -2, 1, 5 ]

更新於: 2020-12-11

251 次瀏覽

開始你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.