股价序列算法题

package algorithm

import scala.math.BigDecimal.RoundingMode

/**
 * 算法题:给你一个股价序列,告诉你每个时间点的股价,问你什么时候买什么时候卖获利最大。时间复杂度越低越好。
 *
 * 动态规划:
 * 转换为后面数减去前面数的最大差
 * 初始最大值为a[length-1]
 * 初始最小值为a[0]
 * 从后向前循环,循环到当前节点a[i]时,可以知道a[i+1]到a[length-1]中的最大值,用最大值减去当前a[i],如果结果大于之前的最大差,则更新最大值,最小值和最大差(即到达当前值时的最大差);并且如果当前值大于之前的最大值,同时更新最大值
 * 也可以反过来,从前向后,记录最小值的方式
 * args format 05:00-23,06:00-15,07:00-8,08:00-4,09:00-3,10:00-1
 * @author GrapeBaBa
 *
 */
object BestBenefit extends App {

  case class Node(time: String, price: BigDecimal)

  def bestBenefit(seq: Array[Node]) = {
    if (seq.length < 2)
      println("args length must equal or larger than 2")
    else {
      var result = (seq.head, seq.last, (seq.last.price - seq.head.price).setScale(2, RoundingMode.HALF_UP))
      var currentMax = seq.last
      for (temp <- seq.reverse.drop(1)) {
        if ((currentMax.price - temp.price) > result._3)
          result = (temp, currentMax, (currentMax.price - temp.price).setScale(2, RoundingMode.HALF_UP))
        if (temp.price > currentMax.price)
          currentMax = temp
      }
      result
    }
  }

  if (args.length < 1)
    println("please input args")
  else {
    val seq = args(0).split(",").map(s => {
      val node = Node(s.split("-")(0), BigDecimal(s.split("-")(1)))
      node
    })

    bestBenefit(seq) match {
      case tuple: (Node, Node, BigDecimal) =>
        println("buy time:" + tuple._1.time + " buy price:" + tuple._1.price + " sell time:" + tuple._2.time + " sell price:" + tuple._2.price + " best benefit:" + tuple._3)
      case _ =>
    }
  }

}

你可能感兴趣的:(股价序列算法题)