scalafunctional-programmingkadanes-algorithm

Kadane's Algorithm in Scala


Does anyone have a Scala implementation of Kadane's algorithm done in a functional style?

Edit Note: The definition on the link has changed in a way that invalidated answers to this question -- which goes to show why questions (and answers) should be self-contained instead of relying on external links. Here's the original definition:

In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers (containing at least one positive number) which has the largest sum. For example, for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.


Solution

  • What about this, if an empty subarray is allowed or the input array cannot be all negative:

    numbers.scanLeft(0)((acc, n) => math.max(0, acc + n)).max
    

    Or, failing the conditions above this (which assumes the input is non-empty):

    numbers.tail.scanLeft(numbers.head)((acc, n) => (acc + n).max(n)).max