

  import io.StdIn._
  object Main extends App {
    val diamonds = Input(readInt(), readLine(), readLine()).diamonds().foldLeft[Diamonds](Diamonds(Nil)) { (purchased: Diamonds, diamond: Diamond) =>
      val next = purchased.add(diamond)
      if (next.value() > purchased.value() && next.cost() < purchased.cost()) next
      else purchased
    }

    println(diamonds.value())
  }

  case class Input(numberOfDiamond: Int, values: Seq[Int], costs: Seq[Int]) {
    def diamonds(): Seq[Diamond] = {
      values.zip(costs).map { case (value, cost) => Diamond.apply(value, cost) }
    }
  }

  object Input {
    def apply(n: Int, values: String, costs: String): Input = {
      Input(n.toInt, values.split(' ').map(_.toInt), costs.split(' ').map(_.toInt))
    }
  }

case class Diamond(value:Int, cost: Int)

case class Diamonds(values: Seq[Diamond]) {
  def value(): Int =
    values.foldLeft(0)(_ + _.value)

  def cost(): Int =
    values.foldLeft(0)(_ + _.cost)

  def add(diamond: Diamond): Diamonds = Diamonds(values :+ diamond)
}