Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 266
S0rin Avatar asked Jan 28 '12 00:01

S0rin


1 Answers

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
like image 90
Heiko Seeberger Avatar answered Sep 25 '22 09:09

Heiko Seeberger