Kadane's Algorithm in Scala

后端 未结 3 956
我在风中等你
我在风中等你 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
    
    0 讨论(0)
  • 2021-02-20 12:10

    I prefer the folding solution to the scan solution -- though there's certainly elegance to the latter. Anyway,

    numbers.foldLeft(0 -> 0) {
      case ((maxUpToHere, maxSoFar), n) =>
        val maxEndingHere = 0 max maxUpToHere + n
        maxEndingHere -> (maxEndingHere max maxSoFar)
    }._2
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题