Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

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 ]