Kadane's Algorithm in Scala

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

提交回复
热议问题