Skip to content

Latest commit

 

History

History
39 lines (27 loc) · 1.14 KB

maximum-subarray-sum.md

File metadata and controls

39 lines (27 loc) · 1.14 KB

Maximum subarray sum 5 Kyu

LINK TO THE KATA - ALGORITHMS LISTS DYNAMIC PROGRAMMING FUNDAMENTALS PERFORMANCE

Description

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
// should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.

Solution

const maxSequence = arr => {
  let maxSoFar = 0
  let maxEndingHere = 0

  for (let i = 0; i < arr.length; i++) {
    maxEndingHere += arr[i]

    if (maxEndingHere < 0) maxEndingHere = 0

    if (maxSoFar < maxEndingHere) maxSoFar = maxEndingHere
  }

  return maxSoFar
}