Kadane's Algorithm in Scala

后端 未结 3 954
我在风中等你
我在风中等你 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:11

    The following code returns the start and end index as well as the sum:

    
    import scala.math.Numeric.Implicits.infixNumericOps
    import scala.math.Ordering.Implicits.infixOrderingOps
    
    case class Sub[T: Numeric](start: Index, end: Index, sum: T)
    
    def maxSubSeq[T](arr: collection.IndexedSeq[T])(implicit n: Numeric[T]) =
      arr
        .view
        .zipWithIndex
        .scanLeft(Sub(-1, -1, n.zero)) {
          case (p, (x, i)) if p.sum > n.zero => Sub(p.start, i, p.sum + x)
          case (_, (x, i))                   => Sub(i, i, x)
        }
        .drop(1)
        .maxByOption(_.sum)
    

提交回复
热议问题