/**
  * Created by ivan-pifagor on 4/23/17.
  */
import scala.io.StdIn.readLine
object Main {
    def main(args: Array[String]): Unit = {
        val K = readLine().split(" ").map(_.toLong)
        val A = readLine().split(" ").map(_.toLong)
        val m = A.min
        if (A.forall(a => ( a - m) % K(1) == 0 )){
            println(A.map(a => (a - m) / K(1)).sum)
        }else {
            println(-1)
        }
    }

}

import io.StdIn.readLine

object A extends App {
  val Array(n, k) = readLine.split(' ').map(_.toInt)
  val xs = readLine.split(' ').map(_.toLong)
  val m = xs.min
  if (xs.exists(x => (x - m) % k != 0)) println("-1")
  else{
    val u = xs.view.map(x => (x - m) / k).sum
    println(u)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val k = arr(1)
    var secondCount = 0L
    var shares = io.StdIn.readLine().split(" ").map(_.toInt)

    val rest = shares.head % k
    if (shares.exists(_ % k != rest)) println(-1) else {
      val minVal = shares.min
      shares.foreach(i => secondCount += (i - minVal) / k)
      println(secondCount)
    }
  }
}

object _793A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, k = read[Int]
    val prices = read[Seq, Long](n)
    val smallest = prices.min
    val target = prices.map(_ - smallest)

    val ans = when(target.forall(_%k == 0)) {
      target.sumWith(_/k)
    }

    write(ans.getOrElse(-1))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object A extends App {

  val arr = io.StdIn.readLine().split(" ").map(_.toLong);
  val count = arr(1)
  val arr2 = io.StdIn.readLine().split(" ").map(_.toLong);
  val min = arr2.min

  val counts = arr2.map {
    case x if (x - min) % count == 0 => (x - min) / count
    case x if (x - min) % count != 0 => -1
  }
  val answer = counts.find(x => x == -1).getOrElse(counts.sum)
  print(answer)
}

object Main {
  def main(args: Array[String]): Unit = {
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val k = arr(1)
    var secondCount = 0
    var shares = io.StdIn.readLine().split(" ").map(_.toInt)

    val rest = shares.head % k
    if (shares.exists(_ % k != rest)) println(-1) else {
      val minVal = shares.min
      shares.foreach(i => secondCount += (i - minVal) / k)
      println(secondCount)
    }
  }
}

object Main {
    def main(args: Array[String]): Unit = {
        val K = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        val A = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        val m = A.min
        if (A.forall(a => ( a - m) % K(1) == 0 )){
            println(A.map(a => (a - m) / K(1)).sum)
        }else {
            println(-1)
        }
    }

}


import scala.io.StdIn._
import scala.collection.mutable.ArraySeq

object Codeforces extends App {
  val beauty = readLine()
  var max: Int = 0
  var aCount: Int = 0
  var bCount: Int = 0
  val a = beauty.map(c => {
    if (c == 'a')
      aCount += 1
    aCount
  }).toArray
  val b = beauty.map(c => {
    if (c == 'b')
      bCount += 1
    bCount
  }).toArray
  for (i <- 0 to beauty.length) {
    for (j <- i to beauty.length) {
      var current: Int = 0
      if (i > 0) // left A
        current += a(i - 1)
      if (j > 0) { // center B
        current += b(j - 1)
        if (i > 0)
          current -= b(i - 1)
      }
      if (j > 0)
        current += a(a.length - 1) - a(j - 1)
      max = math.max(max, current)
    }
  }
  println(max)
}

object _877B extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO): io.type = {
    val s = io.read[String]
    val n = s.length

    def count(from: Int, until: Int, prefixSum: IndexedSeq[Int]) = {
      assert(from <= until)
      prefixSum(until) - prefixSum(from)
    }

    val as = s.scanLeft(0) {
      case (i, 'a') => i + 1
      case (i, _) => i
    }

    val bs = s.scanLeft(0) {
      case (i, 'b') => i + 1
      case (i, _) => i
    }

    def length(l: Int, r: Int) = count(0, l, as) + count(l, r, bs) + count(r, n, as)

    var ans = 0
    for {
      i <- 0 to n
      j <- i to n
    } ans = ans max length(i, j)

    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Long](n)
        val len = new Array[Long](n)
        val edges = new Array[HashSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new HashSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            len(i) = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(len(i) + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(len(i) * spines(i))
        }
        println(result)
    }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
    val g = Array.fill(n)(ArrayBuffer[Int]())
    val len = Array.fill(n)(1L)
    val ct = Array.fill(n)(0L)
    for (i <- 0 until m) {
      val Array(u, v) = StdIn.readLine().split(" ").map(_.toInt - 1)
      g(u).append(v)
      g(v).append(u)
      ct(u) += 1
      ct(v) += 1
    }
    for (v <- 0 until n) {
      for (u <- g(v) if u > v) {
        len(u) = len(u).max(len(v) + 1)
      }
    }
    var ans = 0L
    for (v <- 0 until n) {
      ans = ans.max(len(v) * ct(v))
    }
    println(ans)
  }
}

import scala.collection.mutable
import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)

  val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>
    Seq((j, i), (i, j))
  }
  val mapOfSegments = listOfSegments.groupBy(_._1)

  val mapOfTail = mutable.Map[Int, Int]()

  def calcBeauty(point: Int): Long = {
    val listOfSpine = mapOfSegments.getOrElse(point, Nil)
    val tail = listOfSpine.filter { case (s, e) => e < s }.map { p =>
      mapOfTail(p._2)
    } match {
      case l if l.isEmpty => 1
      case l => l.max + 1
    }

    mapOfTail(point) = tail
    tail.toLong * listOfSpine.length
  }

  val output = {
    for {
      i <- 1 to numOfPoints
    } yield {
      calcBeauty(i)
    }
  }.max

  println(output)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val length = Array.ofDim[Int](n)
  val weight = Array.ofDim[Int](n)
  val edgesUp = Array.fill[List[Int]](n){ Nil }
  val edgesDown = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edgesDown(max) ::= min
    edgesUp(min) ::= max
  }

  def calcLength(start: Int): Int = {
    val children = edgesDown(start)
    if (children.isEmpty) {
      1
    } else {
      val childrenLength = length(children.maxBy(length))
      childrenLength + 1
    }
  }

  (0 until n).foreach(i => length(i) = calcLength(i))

  println(length.zip(weight).map(i => i._1.toLong * i._2).max)

}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)

  val degs = Array.fill(n) { 0 }
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u max v) += u min v
    degs(u) += 1
    degs(v) += 1
  }

  val adjs = adjBuilders.map(_.result)
  val maxDepths = Array.fill(n) { 1 }

  for (u <- 0 until n) {
    for (v <- adjs(u)) {
      maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1)
    }
  }

  val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max

  println(res)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)

  val degs = Array.fill(n) { 0 }
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u max v) += u min v
    degs(u) += 1
    degs(v) += 1
  }

  val adjs = adjBuilders.map(_.result)
  val maxDepths = Array.fill(n) { 1 }

  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val color = Array.fill(n)(0)

  def dfs(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (color(v) == 0) dfs(v)
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs(i)

  val sorted = sortedBuilder.result

  for (u <- sorted) {
    for (v <- adjs(u)) {
      maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1)
    }
  }

  val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max

  println(res)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)

  val degs = Array.fill(n) { 0 }
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u max v) += u min v
    degs(u) += 1
    degs(v) += 1
  }

  val adjs = adjBuilders.map(_.result)
  val maxDepths = Array.fill(n) { 1 }

  val sorted = mutable.ArrayBuffer.empty[Int]

  val color = Array.fill(n)(0)

  def dfs(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (color(v) == 0) dfs(v)
      i += 1
    }
    color(u) = 2
    sorted += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs(i)

  for (u <- sorted) {
    for (v <- adjs(u)) {
      maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1)
    }
  }

  val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max

  println(res)
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
    val g = Array.fill(n)(ArrayBuffer[Int]())
    val len = Array.fill(n)(1)
    val ct = Array.fill(n)(0)
    for (i <- 0 until m) {
      val Array(u, v) = StdIn.readLine().split(" ").map(_.toInt - 1)
      g(u).append(v)
      g(v).append(u)
      ct(u) += 1
      ct(v) += 1
    }
    for (v <- 0 until n) {
      for (u <- g(v) if u > v) {
        len(u) = len(u).max(len(v) + 1)
      }
    }
    var ans = 0
    for (v <- 0 until n) {
      ans = ans.max(len(v) * ct(v))
    }
    println(ans)
  }
}

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Long](n)
        val len = new Array[Long](n)
        val edges = new Array[HashSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new HashSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            var k = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(k + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(len(i) * spines(i))
        }
        println(result)
    }
}

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.TreeSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Int](n)
        val len = new Array[Int](n)
        val edges = new Array[TreeSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new TreeSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            var k = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(k + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(1L * len(i) * spines(i))
        }
        println(result)
    }
}

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Int](n)
        val len = new Array[Int](n)
        val edges = new Array[HashSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new HashSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            var k = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(k + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(1L * len(i) * spines(i))
        }
        println(result)
    }
}

import scala.collection.immutable.TreeMap
import scala.collection.mutable
import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)

  val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>
    Seq((j, i), (i, j))
  }
  val mapOfSegments = TreeMap(listOfSegments.groupBy(_._1).toSeq: _*)

  val mapOfTail = mutable.Map[Int, (Int, Int)]()

  def findTail(point: Int): (Int, Int) = {
    mapOfTail.getOrElseUpdate(point,
      mapOfSegments.getOrElse(point, Nil).filter { case (s, e) => e > s }.map { p =>
        findTail(p._2)
      } match {
        case Nil => (1, point)
        case l =>
          val (len, endPoint) = l.maxBy(_._1)
          (len + 1, endPoint)
      }
    )
  }

  val output = {
    for {
      i <- 1 to numOfPoints
    } yield {
      val (tail, endPoint) = findTail(i)
      val spine = mapOfSegments.get(endPoint).map(_.length).get
      tail * spine
    }
  }.max

  println(output)
}

import scala.collection.mutable
import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)

  val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>
    Seq((j, i), (i, j))
  }
  val mapOfSegments = listOfSegments.groupBy(_._1)

  val mapOfTail = mutable.Map[Int, Int]()

  def calcBeauty(point: Int): Long = {
    val listOfSpine = mapOfSegments.getOrElse(point, Nil)
    val tail = listOfSpine.filter { case (s, e) => e < s }.map { p =>
      mapOfTail(p._2)
    } match {
      case l if l.isEmpty => 1
      case l => l.max + 1
    }

    mapOfTail(point) = tail
    tail * listOfSpine.length
  }

  val output = {
    for {
      i <- 1 to numOfPoints
    } yield {
      calcBeauty(i)
    }
  }.max

  println(output)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.ofDim[Boolean](n)
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start)) max
    else {
     visited(start) = true
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)).max)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.fill[Int](n){ -1 }
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start) >= length) max
    else {
      visited(start) = length
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)).max)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.ofDim[Int](n)
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start) >= length) max
    else {
      visited(start) = length
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)).max)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.ofDim[Boolean](n)
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start)) max
    else {
//      visited(start) = true
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)))

}


import scala.language.postfixOps
import java.io._

object CF_260C {

    def main(args: Array[String]) {
        val stdin = new BufferedReader(new InputStreamReader(System.in));
        val stdout = new PrintWriter(new BufferedOutputStream(System.out));
        val inp_args = stdin.readLine.split(" ");
        val n = inp_args(0).toLong;
        val x = inp_args(1).toLong - 1;
        val end_list = stdin.readLine.split(" ").toArray.map(_.toLong);
        val min = end_list.min
        val min_inds = {
            for( i <- 0 until end_list.length if end_list(i) == min )
                yield(i)
        }
        val lower_mins = min_inds filter(_ <= x);
        val start_pos: Int = {
            if( lower_mins.isEmpty )
                min_inds.last
            else
                lower_mins.last
        }
        val tmp_list = end_list.map(_ - min);
        val start_pos_value : Long = min * n + { if( x >= start_pos ) x - start_pos else x + n - start_pos };
        val start_list: Array[Long] =
            for( i <- 0 until tmp_list.length toArray ) yield
                if( i == start_pos )
                    start_pos_value
                else if( ( x >= start_pos && i > start_pos && i <= x ) || ( x < start_pos && ( i > start_pos || i <= x ) ) )
                    tmp_list(i) - 1
                else
                    tmp_list(i)

        for( i <- 0 until start_list.length )
            stdout.print(start_list(i).toString + " ");

        stdout.println();
        stdout.close();
    }
}

object CF260C extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve = {
    val n = nextInt
    val x = nextInt - 1
    var a = (for (i <- 0 until n) yield nextLong).toArray

    var c = 0l
    var min = a.min
    if (min > 0) {
      a = a map { _ - min }
      c = min * n
    }

    var finished = false
    var i = x
    while (!finished) {
      if (a(i) == 0) {
        finished = true
        a(i) = c
      } else {
        a(i) -= 1
        c += 1
        i = if (i == 0) n - 1 else i - 1
      }
    }

    a foreach((x) => out.print(x + " "))
    out.println()
  }

  try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }
}

import java.io._

object CF_260C {

    def main(args: Array[String]) {
        val stdin = new BufferedReader(new InputStreamReader(System.in));
        val stdout = new PrintWriter(new BufferedOutputStream(System.out));
        val inp_args = stdin.readLine.split(" ");
        val n = inp_args(0).toInt;
        val x = inp_args(1).toInt - 1;
        val end_list = stdin.readLine.split(" ").toArray.map(_.toInt);
        val min = end_list.min
        val min_inds = {
            for( i <- 0 until end_list.length if end_list(i) == min )
                yield(i)
        }
        val lower_mins = min_inds filter(_ <= x);
        val start_pos: Int = {
            if( lower_mins.isEmpty )
                min_inds.last
            else
                lower_mins.last
        }
        val tmp_list = end_list.map(_ - min);
        val start_pos_value = min * n + { if( x >= start_pos ) x - start_pos else x + n - start_pos };
        val start_list =
            for( i <- 0 until tmp_list.length ) yield
                if( i == start_pos )
                    start_pos_value
                else if( ( x >= start_pos && i > start_pos ) || ( x < start_pos && ( i > start_pos || i <= x ) ) )
                    tmp_list(i) - 1
                else
                    tmp_list(i)

        for( i <- 0 until start_list.length )
            stdout.print(start_list(i).toString + " ");

        stdout.println();
        stdout.close();
    }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).toSet
  println((1 to 3001).find{i => !data.contains(i)}.get)
}

object P027A {
  def main(args: Array[String]) = {
    var s = scala.collection.mutable.Set((1 to readInt+1) :_*)
    readLine.split(' ').map(x => x.toInt).foreach(x => s.remove(x))
    println(s min)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt).toSet
    val rest = Set() ++ ((1 to 3001)) -- a
    println(rest.min)
  }
}


object A extends App {
  case class Stat(p: Int, c: Int)

  implicit def arr2stat(arr: Array[Int]): Stat = arr match {
    case Array(p, c) => Stat(p, c)
    case _           => throw new IllegalArgumentException
  }

  private def isCorrect(s: Stat): Boolean = s.p >= s.c

  private def isCorrect(s1: Stat, s2: Stat): Boolean =
    isCorrect(s1) && isCorrect(s2) &&
      s1.p <= s2.p && s1.c <= s2.c && (s2.c - s1.c) <= (s2.p - s1.p)

  @scala.annotation.tailrec
  private def isCorrect(stats: List[Stat]): Boolean = stats match {
    case Nil              => true
    case s :: Nil         => isCorrect(s)
    case s1 :: s2 :: rest => isCorrect(s1, s2) && isCorrect(s2 :: rest)
  }

  val t = scala.io.StdIn.readInt()

  val stats = (0 until t)
    .foldLeft(List.empty[List[Stat]]) { (acc1, _) =>
      val n = scala.io.StdIn.readInt()

      val ss = (0 until n)
        .foldLeft(List.empty[Stat]) { (acc2, _) =>
          val s = scala.io.StdIn.readLine().split(" ").map(_.toInt)
          s :: acc2
        }
        .reverse

      ss :: acc1
    }
    .reverse

  val answers = stats.map(isCorrect)

  answers.foreach(if (_) println("YES") else println("NO"))
}

import scala.io.StdIn.readLine

object Main {
    def main(args: Array[String]) = {
        val T = readLine.toInt
        for (_ <- 0 until T) {
            val n = readLine.toInt
            val (p, c) = (0 until n)
                                    .map(_ => readLine.split(' ').map(_.toInt))
                                    .map{ case Array(x, y) => (x, y) }
                                    .unzip
            val p_diff =  p.zip(p drop 1) map {case (x, y) => y - x}
            val c_diff =  c.zip(c drop 1) map {case (x, y) => y - x}

            if (c_diff.forall(_ >= 0) && (c_diff zip p_diff).forall{case (c, p) => c <= p} && c.head <= p.head) {
                println("YES")
            } else {
                println("NO")
            }
        }
    }
}

import scala.io.StdIn.readLine

object Main {
    def main(args: Array[String]) = {
        val T = readLine.toInt
        for (_ <- 0 until T) {
            val n = readLine.toInt
            val (p, c) = (0 until n)
                                    .map(_ => readLine.split(' ').map(_.toInt))
                                    .map{ case Array(x, y) => (x, y) }
                                    .unzip
            val p_diff =  p.zip(p drop 1) map {case (x, y) => y - x}
            val c_diff =  c.zip(c drop 1) map {case (x, y) => y - x}

            if (c_diff.forall(_ >= 0) && (c_diff zip p_diff).forall{case (c, p) => c <= p}) {
                println("YES")
            } else {
                println("NO")
            }
        }
    }
}


object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ans = 1L * a * math.abs(x - y) + math.min(2L * a, 1L * b) * math.min(x, y)

    println(ans)
  }
}

import scala.io.StdIn.readLine

object A {
  def solution(x: Int, y: Int, a: Long, b: Long): Long =
    if (y < x)
      solution(y, x, a, b)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {}

  for (_ <- 1 to nextInt) {
    val x, y, a, b = nextLong
    val res1 = a * Math.abs(x - y) + b * Math.min(x, y)
    val res2 = a * (x + y)

    out.println(res1 min res2)
  }

  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toLong)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val ans = a * math.abs(x - y) + math.min(a + a, b) * math.min(x, y)

    println(ans)
  }
}

import scala.io.StdIn.readLine
import math._

object A {
  def solution(x: Int, y: Int, a: Int, b: Int): Int =
    if (abs(y) < abs(x))
      solution(y, x, a, b)
    else if (x < 0 && y < 0)
      solution(-x, -y, a, b)
    else if (x < 0 && y > 0)
      a * (y - x)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

import scala.io.StdIn.readLine
import math._

object A {
  def solution(x: Int, y: Int, a: Int, b: Int): Int =
    if (abs(y) < abs(x))
      solution(y, x, a, b)
    else if (x < 0 && y < 0)
      solution(-y, -x, a, b)
    else if (x < 0 && y > 0)
      a * (y - x)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

import scala.io.StdIn.readLine

object A {
  def solution(x: Int, y: Int, a: Int, b: Int): Int =
    if (y < x)
      solution(y, x, a, b)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {}

  for (_ <- 1 to nextInt) {
    val x, y, a, b = nextLong
    val res = a * Math.abs(x - y) + b * Math.min(x, y)

    out.println(res)
  }

  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toLong)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val ans = a * math.abs(x - y) + math.min(a, b) * math.min(x, y)

    println(ans)
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ans = 1L * a * math.abs(x - y) + math.min(2L * a * x, 1L * b * x)

    println(ans)
  }
}


import scala.io.StdIn._

object ProblemA extends App {
  val n = readInt()
  val A: Seq[Int] = readLine().split(' ').map(_ toInt)
  val B: Seq[Int] = readLine().split(' ').map(_ toInt)
  var maxbs = Seq(-1, -1)
  for (b <- B) {
    maxbs = Seq(maxbs(0).max(b), maxbs(1)).sorted
  }
  println(if (maxbs.sum >= A.map(BigInt(_)).sum) "YES" else "NO")
}

object A extends App {
  val n = scala.io.StdIn.readLine().toLong
  val A = scala.io.StdIn.readLine().split(" ").foldLeft(0L)(_ + _.toLong)
  val b = scala.io.StdIn.readLine().split(" ").map(_.toLong).sortWith(_ > _)

  if (b(0) + b(1) >= A) println("YES")
  else println("NO")
}

import scala.io.StdIn._

object ProblemA extends App {
  val n = readInt()
  val A: Seq[Int] = readLine().split(' ').map(_ toInt)
  val B: Seq[Int] = readLine().split(' ').map(_ toInt)
  var maxbs = Seq(-1, -1)
  for (b <- B) {
    maxbs = Seq(maxbs(0), maxbs(1).max(b)).sorted(Ordering[Int].reverse)
  }
  println(if (maxbs.sum >= A.sum) "YES" else "NO")
}

import scala.io.StdIn._

object ProblemA extends App {
  val n = readInt()
  val A: Seq[Int] = readLine().split(' ').map(_ toInt)
  val B: Seq[Int] = readLine().split(' ').map(_ toInt)
  var maxbs = Seq(-1, -1)
  for (b <- B) {
    maxbs = Seq(maxbs(0).max(b), maxbs(1)).sorted
  }
  println(if (maxbs.map(BigInt(_)).sum >= A.sum) "YES" else "NO")
}

object A extends App {
  val n = scala.io.StdIn.readLine().toInt
  val A = scala.io.StdIn.readLine().split(" ").foldLeft(0)(_ + _.toInt)
  val b = scala.io.StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _)

  if (b(0) + b(1) >= A && b(0) < A) println("YES")
  else println("NO")
}

object A extends App {
  val n = scala.io.StdIn.readLine().toInt
  val A = scala.io.StdIn.readLine().split(" ").foldLeft(0)(_ + _.toInt)
  val b = scala.io.StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _)

  if (b(0) + b(1) >= A) println("YES")
  else println("NO")
}


//package codeforces.contests._1359

object _4 {

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val seq = 0 +: io.StdIn.readLine.split(" ").map(_.toInt) // 1 based
    val prefix = seq.scanLeft(0)(_ + _).tail

    @scala.annotation.tailrec
    def calculateLeftView(idx: Int = 1,
                          decreasingStack: List[(Int, Int)] = Nil, // stack for indices and there max sub array sum ending at them
                          resultList: List[Int] = Nil): List[Int] = {
      if (idx > n) resultList
      else {
        val (toConsider, rest) = decreasingStack.partition { case (i, _) => seq(i) <= seq(idx) }

        val resultSum = toConsider.foldLeft(seq(idx)) { case (acc, (i, maxSum)) =>
          val rangeSum = prefix(idx) - prefix(i) // without i
          acc max ((maxSum + rangeSum) max (seq(i) + rangeSum))
        }

        calculateLeftView(idx + 1, (idx, resultSum) :: rest, resultSum :: resultList)
      }
    }

    @scala.annotation.tailrec
    def calculateRightView(idx: Int = n,
                           decreasingStack: List[(Int, Int)] = Nil, // stack for indices and there max sub array sum ending at them
                           resultList: List[Int] = Nil): List[Int] = {
      if (idx == 0) resultList
      else {
        val (toConsider, rest) = decreasingStack.partition { case (i, _) => seq(i) <= seq(idx) }

        val resultSum = toConsider.foldLeft(seq(idx)) { case (acc, (i, maxSum)) =>
          val rangeSum = prefix(i - 1) - prefix(idx - 1)
          acc max ((maxSum + rangeSum) max (seq(i) + rangeSum))
        }

        calculateRightView(idx - 1, (idx, resultSum) :: rest, resultSum :: resultList)
      }
    }

    val leftView = calculateLeftView().reverse
    val rightView = calculateRightView()
    println {
      leftView.zip(rightView).zipWithIndex.foldLeft(0) { case (acc, ((lSum, rSum), i)) => acc max (lSum + rSum - 2 * seq(i + 1)) }
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val _ = StdIn.readLine().toInt
    val arr = StdIn.readLine.trim.split(" ").map(_.toInt)
    def maxSubArrayEx(nums: Array[Int], max: Int): Int = {
      var res: Long = 0
      var cur: Long = 0
      for (i <- nums.indices ) {
        if (nums(i) > max) cur = 0
        else {
          cur = math.max(cur + nums(i),0)
          res = math.max(res, cur-max)
        }
      }
      res.toInt
    }
    println((1 to 30).map(maxSubArrayEx(arr, _)).max)
  }
}

object D extends App {
  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans = (0 to 30).foldLeft(0) {
    case (ans, m) =>
      ans max (an
        .foldLeft((0, 0)) {
          case ((subSum, partSum), a) =>
            if (a > m) (subSum, 0)
            else (subSum max (partSum + a), 0 max (partSum + a))
        }
        ._1 - m)
  }

  println(ans)
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    val arr = StdIn.readLine.trim.split(" ").map(_.toInt)
    def maxSubArrayEx(nums: Array[Int]): Int = {
      var res: Long = 0
      var cur: Long = nums(0)
      var emax: Long = nums(0)
      for (i <- 1 until nums.length) {
        if (cur + nums(i) < nums(i)) {
          cur = nums(i)
          emax = nums(i)
        } else {
          cur = cur + nums(i)
          emax = emax max nums(i)
        }
        res = res max (cur - emax)
      }
      res.toInt
    }
    println(maxSubArrayEx(arr))
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    val arr = StdIn.readLine.trim.split(" ").map(_.toInt)
    def maxSubArrayEx(nums: Array[Int]): Int = {
      var res: Long = 0
      var cur: Long = nums(0)
      var emax: Long = nums(0)
      for (i <- 1 until nums.length) {
        if (cur + nums(i) < nums(i)) {
          cur = nums(i)
          emax = nums(i)
        } else {
          cur = cur + nums(i)
          emax = emax max nums(i)
        }
        res = res max (cur - emax)
      }
      res.toInt
    }
    maxSubArrayEx(arr)
  }
}

object D extends App {
  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans = (0 to 30).map { m =>
    an.foldLeft((an.head, 0)) {
        case ((subSum, partSum), a) =>
          if (a > m) (subSum, 0)
          else (subSum max (partSum + a), 0 max (partSum + a))
      }
      ._1 - m
  }.max

  println(ans)

}


object CF499D extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val m = in.nextInt
  val n = in.nextInt

  var count = -1
  def ask(question: Int): Int = {
    count += 1
    out.println(question)
    out.flush

    val answer = in.nextInt
    if (answer == 0 || answer == -2) {
      out.close
      System.exit(0)
    }
    answer
  }

  // log(10^9)/log(2) = 29.9
  // so we can waste 30 questions to determine the lie sequence and still have 30 left to find the answer
  // All answers should be 1
  val lieSequence = new Array[Int](30).map(_ => ask(1)).map(_ != 1).take(n)

  var min = 1
  var max = m

  while (true) {
    // Binary search
    val question = (min + max)/2
    val answer = (ask(question) == 1) ^ lieSequence(count%n) // real answer
    if (answer) {
      // more
      min = question + 1
    } else {
      // less
      max = question - 1
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val M, N = ni()

    case class Answer(x: Int)

    def query(y: Int): Either[Answer, Int] = {
//      debug(s"query $y")
      out.println(y)
      out.flush()
      val res = ni()
      if (res == 0) Left(Answer(y))
      else Right(res)
    }

    def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {
      if (i == N) Right(p)
      else {
        // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。
        // -1がくるかどうかでpを判定する
        query(i + 1).right flatMap { res =>
          p(i) = res
          makeP(i + 1, p)
        }
      }
    }

    def search(p: Array[Int]): Either[Answer, _] = {
      def step(i: Int, l: Int, r: Int): Either[Answer, _] = {
//        debug(s"step($i, $l, $r)")
        if (r - l == 1) {
//          debug(s"found $r")
          query(r)
        } else {
          val mid = (l + r) / 2 + 1
          query(mid).right flatMap { res =>
            if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y
            else step(i + 1, l, mid - 1) // -1 => x < y =>
          }
        }
      }

      step(0, N, M)
    }

    // 結果を出力しなくていい。0が帰った時点で終わり
    for {
      p <- makeP(0, Array.ofDim[Int](N)).right
      _ <- search(p).right
    } ()
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object CF499D extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val m = in.nextInt
  val n = in.nextInt

  var count = -1
  def ask(question: Int): Int = {
    count += 1
    out.println(question)
    out.flush

    val answer = in.nextInt
    if (answer == 0 || answer == -2) {
      out.close
      System.exit(0)
    }
    answer
  }

  // log(10^9)/log(2) = 29.9
  // so we can waste up to 30 questions to determine the lie sequence and still have 30 left to find the answer
  // Ask n times "1", all answers should be 1 (meaning distance > 1)
  val lieSequence = new Array[Int](n).map(_ => ask(1)).map(_ != 1)

  var min = 1
  var max = m

  while (true) {
    // Binary search
    val question = (min + max)/2
    val answer = (ask(question) == 1) ^ lieSequence(count%n) // real answer
    if (answer) {
      // more
      min = question + 1
    } else {
      // less
      max = question - 1
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val M, N = ni()

    case class Answer(x: Int)

    def query(y: Int): Either[Answer, Int] = {
//      debug(s"query $y")
      out.println(y)
      out.flush()
      val res = ni()
      if (res == 0) Left(Answer(y))
      else Right(res)
    }

    def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {
      if (i == N) Right(p)
      else {
        // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。
        // -1がくるかどうかでpを判定する
        query(i + 1).right flatMap { res =>
          p(i) = res
          makeP(i + 1, p)
        }
      }
    }

    def search(p: Array[Int]): Either[Answer, _] = {
      def step(i: Int, l: Int, r: Int): Either[Answer, _] = {
//        debug(s"step($i, $l, $r)")
        if (r - l == 1) {
//          debug(s"found $r")
          query(r)
        } else {
          val mid = (l + r) / 2
          query(mid).right flatMap { res =>
            if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y
            else step(i + 1, l, mid) // -1 => x < y =>
          }
        }
      }

      step(0, N, M)
    }

    // 結果を出力しなくていい。0が帰った時点で終わり
    for {
      p <- makeP(0, Array.ofDim[Int](N)).right
      _ <- search(p).right
    } ()
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val M, N = ni()

    case class Answer(x: Int)

    def query(y: Int): Either[Answer, Int] = {
//      debug(s"query $y")
      out.println(y)
      out.flush()
      val res = ni()
      if (res == 0) Left(Answer(y))
      else Right(res)
    }

    def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {
      if (i == N) Right(p)
      else {
        // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。
        // -1がくるかどうかでpを判定する
        query(i + 1).right flatMap { res =>
          p(i) = res
          makeP(i + 1, p)
        }
      }
    }

    def search(p: Array[Int]): Either[Answer, _] = {
      def step(i: Int, l: Int, r: Int): Either[Answer, _] = {
//        debug(s"step($i, $l, $r)")
        if (r - l == 1) {
//          debug(s"found $r")
          query(r)
        } else {
          val mid = (l + r) / 2
          query(mid).right flatMap { res =>
            if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y
            else step(i + 1, l, mid - 1) // -1 => x < y =>
          }
        }
      }

      step(0, N, M)
    }

    // 結果を出力しなくていい。0が帰った時点で終わり
    for {
      p <- makeP(0, Array.ofDim[Int](N)).right
      _ <- search(p).right
    } ()
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


object A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      val x: Long = Math.max(n, k)
      var res: Long = Math.max(1, x / n)
      if (n * res % k > 0) res += 1

      out.println(res)
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n){
        if(n % k == 0){
          println(1)
        } else {
          k *= n / k + 1
          println(k / n + 1)
        }
      } else {
        if(k % n == 0) println(k / n)
        else println(k / n + 1)
      }
      T -= 1
    }
  }
}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      val x = Math.max(n, k)
      var res = Math.max(1, x / n)
      if (n * res % k > 0) res += 1

      out.println(res)
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

//package codeforces.CF1476

import scala.io.StdIn._

object SolutionA extends App {
  (1 to readInt()).foreach {
    _ =>
      val strings = readLine().split(" ")
      val n = strings.head.toLong
      val k = strings.last.toLong
      if (n <= k) {
        println(k / n + (k % n != 0).compare(false))
      } else {
        val realK = (n / k + (n % k != 0).compare(false)) * k
        println(realK / n + (realK % n != 0).compare(false))
      }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n){
        if(n % k == 0){
          println(1)
        } else {
          k *= n / k + 1
        }
      } else {
        if(k % n == 0) println(k / n)
        else println(k / n + 1)
      }
      if(k < n){
        val temp = n / k
        k *= temp + 1
      }

      T -= 1
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n){
        val temp = n / k
        k *= temp + 1
      }
      if(k % n == 0) println(k / n)
      else println(k / n + 1)
      T -= 1
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n) k *= 2
      if(k % n == 0) println(k / n)
      else println(k / n + 1)
      T -= 1
    }
  }
}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      var res = Math.max(1, k / n)
      if (k % n > 0) res += 1

      out.println(res)
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, m = r.read[Int]
    import Utils._
    val xs = r.read[List[Int]](m).sorted.group(_ == _)

    if (xs.length < n) {
      println(0)
    } else {
      println(xs.map(_.length).min)
    }
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

object Solution {

    def main(args: Array[String]) {
        val inp = readLine.split(" ").map(_.toInt)
        val arr = Array.ofDim[Int](inp(0))
        readLine.split(" ").foreach(f => arr(f.toInt - 1) += 1)
        print(arr.min)
    }
}

object Tetrix extends App {
  val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
  val n = firstinput(0)
  val m = firstinput(1)
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList

  val emptyFreqMap = (1 to n).map( x => (x, 0)).toMap
  val distinctSquaresValues = emptyFreqMap.keys.size
  val freqMap = squares.groupBy( x => x).mapValues( _.length )
  val finalMap = emptyFreqMap ++ freqMap
  val minFq = finalMap.minBy( _._2 )._2

  val points =
    if(distinctSquaresValues < n) 0
    else minFq

  println(points)
}

object Tetrix extends App {
  val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
    // Seq(1, 1000)
    // Seq(3, 9)
    // Console.in.readLine().split(" ").map( _.toInt).toList
  val n = firstinput(0) // cantidad de valores distintos
  val m = firstinput(1)
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList
    // (1 to 1000).map(x => 1).toList
    // List(1, 1, 2, 2, 2, 3, 1, 2, 3)
    // Console.in.readLine().split(" ").map( _.toInt).toList

  val emptyFreqMap = (1 to n).map( x => (x, 0)).toMap
  val distinctSquaresValues = emptyFreqMap.keys.size
  val freqMap = squares.groupBy( x => x).mapValues( _.length )
  val finalMap = emptyFreqMap ++ freqMap
  val maxFq = finalMap.maxBy( _._2 )._2
  val minFq = finalMap.minBy( _._2 )._2

  val resutl =
    if(distinctSquaresValues < n) {
      0
    } else if (distinctSquaresValues == 1) {
      maxFq
    } else {
      minFq
    }

  println(resutl)
}

object A {
  def main(args: Array[String]) {
    val t = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    val n = t(0);
    val m = t(1);
    //println(n, m);
    val s = scala.io.StdIn.readLine();
    var cs = s.split(" ").map( _.toInt );
    //println(cs.size)
    var a = Array.ofDim[Int](n);
    //println(a.size)
    for(c <- cs){
        //println(c - 1)
        //println(cs(i) - 1)
        a(c - 1) += 1;
    }
    var ans = m + m;
    for(i <- 0 until n){
        ans = math.min(ans, a(i))
    }
    println(ans)
  }
}

object problemA {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(n, m) = readArray.map(_.toInt)
        val f = new Array[Int](n)

        val k = readArray().map(_.toInt)

        for (i <- k) {
            f(i - 1) += 1
        }

        println(f.min)

    }
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, m = r.read[Int]
    val xs = r.read[List[Int]](m)

    import Utils._
    println(xs.sorted.group(_ == _).map(_.length).min)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
}

object Utils {
  import scala.math._

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, m = r.read[Int]
    val xs = r.read[List[Int]](m).sorted

    if (xs.length < n) {
      println(0)
    } else {
      import Utils._

      println(xs.sorted.group(_ == _).map(_.length).min)
    }
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
}

object Utils {
  import scala.math._

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

import scala.annotation.tailrec

object Tetrix extends App {
  val _: String = Console.in.readLine()
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList
  @tailrec
  def minFreq(a: List[Int], min: Int, max: Int, freq: Map[Int, Int]): (Int, Int) = a match {
    case Nil => (min, max)
    case x :: xs =>
      val currValue : Int = freq.getOrElse(x, 0)
      val newValue = currValue + 1
      val newFreq: Map[Int, Int] = freq + (x -> newValue)
      if(max <= newValue) {
        minFreq(xs, max, newValue, newFreq)
      } else if(min >= newValue){
        minFreq(xs, newValue, max, newFreq)
      } else {
        minFreq(xs, min, max, newFreq)
      }
  }

  val (min, max) = minFreq(squares, 0, 0, Map.empty[Int, Int])
  println { min }
}

object Tetrix extends App {
  val _ = Console.in.readLine()

  val squares = Console.in.readLine().split(" ").map(_.toInt)
  val x = squares.groupBy(x => x).mapValues(_.length).values.min

  println { x }
}

object Tetrix extends App {
    val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
    val n = firstinput(0)
    val m = firstinput(1)
    val squares = Console.in.readLine().split(" ").map( _.toInt).toList

    def increaseFreq(e: Int, freqMap: Map[Int, Int]): Map[Int, Int] = {
        val currValue = freqMap.getOrElse(e, 0)
        freqMap + (e -> (currValue + 1))
    }

    def pointsOf(Fq: Int, minFq: Int , maxFq: Int): (Int, Int) = {
        if(Fq >= maxFq) (maxFq, Fq)
        else (Fq, maxFq)
    }

    def minFreq(a: List[Int], freqMap: Map[Int, Int], minFq: Int , maxFq: Int): (Int, Map[Int, Int]) = a match {
      case Nil => (minFq, freqMap)
      case x :: xs =>
        val newMap = increaseFreq(x, freqMap)
        val (points, newMax) = pointsOf(newMap(x), minFq, maxFq)
        minFreq(xs, newMap, points, newMax)
    }

    val tablero = Map.empty[Int, Int]
    val initialPoints = 0
    val (min, freq) = minFreq(squares, tablero, minFq = initialPoints, maxFq = 0)

    val result =
      if(1 < freq.keys.size && freq.keys.size < n) 0
      else if (1 == freq.keys.size) min + 1
      else min

    println(result)
}

object Tetrix extends App {
    val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
    val n = firstinput(0)
    val m = firstinput(1)
    val squares = Console.in.readLine().split(" ").map( _.toInt).toList

    def increaseFreq(e: Int, freqMap: Map[Int, Int]): Map[Int, Int] = {
        val currValue = freqMap.getOrElse(e, 0)
        freqMap + (e -> (currValue + 1))
    }

    def pointsOf(Fq: Int, minFq: Int , maxFq: Int): (Int, Int) = {
        if(Fq >= maxFq) (maxFq, Fq)
        else (Fq, maxFq)
    }

    def minFreq(a: List[Int], freqMap: Map[Int, Int], minFq: Int , maxFq: Int): (Int, Map[Int, Int]) = a match {
      case Nil => (minFq, freqMap)
      case x :: xs =>
        val newMap = increaseFreq(x, freqMap)
        val (points, newMax) = pointsOf(newMap(x), minFq, maxFq)
        minFreq(xs, newMap, points, newMax)
    }

    val tablero = Map.empty[Int, Int]
    val initialPoints = 0
    val (min, freq) = minFreq(squares, tablero, minFq = initialPoints, maxFq = 0)

    val result =
      if(freq.keys.size < n) 0
      else min

    println(result)
}

import scala.annotation.tailrec

object Tetrix extends App {
  val _: String = Console.in.readLine()
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList
  @tailrec
  def minFreq(a: List[Int], min: Int, max: Int, freq: Map[Int, Int]): (Int, Int) = a match {
    case Nil => (min, max)
    case x :: xs =>
      val currValue : Int = freq.getOrElse(x, 0)
      val newValue = currValue + 1
      val newFreq: Map[Int, Int] = freq + (x -> newValue)
      if(max <= newValue) {
        minFreq(xs, max, newValue, newFreq)
      } else if(min <= newValue){
        minFreq(xs, min, max, newFreq)
      } else {
        minFreq(xs, newValue, max, newFreq)
      }
  }

  val (min, max) = minFreq(squares, 0, 0, Map.empty[Int, Int])
  println { min }
}