Kadane's Algorithm in Scala

后端 未结 3 911
我在风中等你
我在风中等你 2021-02-20 11:42

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 invali

3条回答
  •  迷失自我
    2021-02-20 12:03

    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
    

提交回复
热议问题