object B651 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n).sorted
    val vis = Array.fill(n)(false)
    for(i <- 0 until n) {
      var pos = -1
      for(j <- i+1 until n if pos == -1 && !vis(j)) {
        if(in(j) > in(i)) {
          pos = j
          vis(pos) = true
        }
      }
    }
    println(vis.count(identity))
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine;
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object Paintings {

  def main (args: Array[String]) {

    //System.setIn(new FileInputStream("./src/paintings.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/paintings.out")))

    var n = readInt()
    var a: Array[Int] = readLine().split(" ").map(_.toInt).sorted

    var same = 0
    var maxSame = 1

    for(i <- 0 until a.length) {
      if(i == 0 || a(i) > a(i - 1)) {
        same = 1
      }
      else {
        same += 1
        maxSame = Math.max(maxSame, same)
      }
    }

    println(n - maxSame)
  }
}

import java.io._
import java.util.Scanner

import scala.collection.mutable.ListBuffer

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      val a = ListBuffer.empty[Int]
      for (i <- 0 until n) {
        val el = reader.nextInt()
        a.append(el)
      }
      var answer = 0
      while (a.nonEmpty) {
        var min = a.min
        a -= min
        var exit = false
        while (!exit) {
          var r: Option[Int] = None
          for (el <- a) if (el > min && (r.isEmpty || r.exists(_ > el))) r = Some(el)
          if (r.isDefined) {
            answer += 1
            min = r.get
            a -= min
          } else {
            exit = true
          }
        }
      }
      writer.print(answer)
    }
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val length = in.next().split(' ').map(_.toInt).groupBy(i => i).maxBy(_._2.length)._2.length
  println(n - length)
}

import java.io._
import java.util._

import scala.collection.mutable

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    val sorted = a.sorted
    var ind = 0
    var ans = 0L
    var previousSize = 0
    while (ind < n) {
      var prev = ind
      while (prev < n && sorted(prev) == sorted(ind)) {
        prev += 1
      }
      ans += Math.min(prev - ind, previousSize)
      previousSize = Math.max(previousSize, prev - ind)
      ind = prev
    }
    out.println(ans)
    return 0
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _651B extends CodeForcesApp {
  override def apply(io: IO) = {
    val data = io[IndexedSeq[Int]]
    io += (data.length - data.counts.values.max)
  }
}
/****************************[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 partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates: Traversable[A] = {
      val elems = mutable.Set.empty[A]
      t collect {case i if !elems.add(i) => i}
    }
    def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}
    def mapTo[B](f: 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 collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def counts: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
  }
  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 IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {
    def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s
  }
  implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))
    def swap: Traversable[(B, A)] = t.map(_.swap)
  }
  implicit class MapExtensions[K, V](val map: Map[K, V]) extends AnyVal {
    def invert: Map[V, Traversable[K]] = map.swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = (map map {case (k, v) => f(k) -> v}).toUniqueMap
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def mod(y: Int) = x - (x/y)*y   //(x/y)*y + (x mod y) == x
    def -->(y: Int) = if (x < y) x to y else y to x
    def nonNegative: Option[Int] = when(x >= 0)(x) //e.g. students.indexOf("Greg").nonNegative
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount = java.lang.Long.bitCount(x)
    def pow(i: Int): Long = if (i == 0) 1 else {
      val h = x pow (i/2)
      if (i%2 == 0) h*h else h*h*x
    }
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse
  def  asc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]]
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): (I => O) = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {
  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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)
  def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  override def +=(obj: Any) = {
    if (isNewLine) isNewLine = false else print(separator)
    print(obj)
    this
  }
  def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t

  def newLine(): this.type = {
    println()
    isNewLine = true
    this
  }

  override def clear() = flush()
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}

class Parser[A](val apply: IO => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _651B extends CodeForcesApp {
  override def apply(io: IO) = {
    var data = io[IndexedSeq[Int]].counts.toMap
    var ans = 0
    while(data.nonEmpty) {
      ans += data.size - 1
      data = data collect {
        case (k, v) if v > 1 => (k, v - 1)
      }
    }
    io += 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 partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates: Traversable[A] = {
      val elems = mutable.Set.empty[A]
      t collect {case i if !elems.add(i) => i}
    }
    def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}
    def mapTo[B](f: 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 counts: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
  }
  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 IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {
    def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s
  }
  implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))
    def swap: Traversable[(B, A)] = t.map(_.swap)
  }
  implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {
    def invert: Map[V, Traversable[K]] = m.swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def mod(y: Int) = x - (x/y)*y   //(x/y)*y + (x mod y) == x
    def -->(y: Int) = if (x < y) x to y else y to x
    def nonNegative: Option[Int] = when(x >= 0)(x) //e.g. students.indexOf("Greg").nonNegative
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount = java.lang.Long.bitCount(x)
    def pow(i: Int): Long = if (i == 0) 1 else {
      val h = x pow (i/2)
      if (i%2 == 0) h*h else h*h*x
    }
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]]
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): (I => O) = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {
  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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)
  def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  override def +=(obj: Any) = {
    if (isNewLine) isNewLine = false else print(separator)
    print(obj)
    this
  }
  def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t

  def newLine(): this.type = {
    println()
    isNewLine = true
    this
  }

  override def clear() = flush()
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}

class Parser[A](val apply: IO => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _651B extends CodeForcesApp {
  override def apply(io: IO) = {
    val data = io[IndexedSeq[Int]].counts.values
    io += (data.sum - data.max)
  }
}
/*
Charity begins at home.
		-- Publius Terentius Afer (Terence)
*/
/****************************[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 partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates: Traversable[A] = {
      val elems = mutable.Set.empty[A]
      t collect {case i if !elems.add(i) => i}
    }
    def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}
    def mapTo[B](f: 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 counts: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
  }
  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 IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {
    def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s
  }
  implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))
    def swap: Traversable[(B, A)] = t.map(_.swap)
  }
  implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {
    def invert: Map[V, Traversable[K]] = m.swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def mod(y: Int) = x - (x/y)*y   //(x/y)*y + (x mod y) == x
    def -->(y: Int) = if (x < y) x to y else y to x
    def nonNegative: Option[Int] = when(x >= 0)(x) //e.g. students.indexOf("Greg").nonNegative
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount = java.lang.Long.bitCount(x)
    def pow(i: Int): Long = if (i == 0) 1 else {
      val h = x pow (i/2)
      if (i%2 == 0) h*h else h*h*x
    }
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]]
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): (I => O) = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {
  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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)
  def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  override def +=(obj: Any) = {
    if (isNewLine) isNewLine = false else print(separator)
    print(obj)
    this
  }
  def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t

  def newLine(): this.type = {
    println()
    isNewLine = true
    this
  }

  override def clear() = flush()
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}

class Parser[A](val apply: IO => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _651B extends CodeForcesApp {
  override def apply(io: IO) = {
    val data = io[IndexedSeq[Int]]
    io += (data.length - data.groupBy(identity).map(_._2.length).max)
  }
}
/****************************[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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with collection.generic.Growable[Any] {
  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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)
  def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  override def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else print(separator)
    print(obj)
    this
  }
  def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t

  def newLine(): this.type = {
    println()
    isNewLine = true
    this
  }

  override def clear() = flush()
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}

class Parser[A](val apply: IO => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _651B extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val c = in[Traversable[Int]].counts

    @tailrec
    def f(acc: Int): Int = if (c.size <= 1) {
      acc
    } else {
      val size = c.size
      c.keys foreach {k =>
        if (c(k) == 1) c.remove(k) else c(k) -= 1
      }
      f(acc + size - 1)
    }

    out += f(0)
  }

  implicit class TraversableExtensions[A](t: Traversable[A]) {
    def counts = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
  }

  def map[K] = new {
    def to[V](default: V): mutable.Map[K, V] = mutable.Map.empty[K, V] withDefaultValue default
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Any
  def main(args: Array[String]): Unit = {
    val (in, out) = (new InputReader(System.in), new OutputWriter(System.out))
    solve(in, out)
    in.close()
    out.close()
  }
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)
  def apply[C[_], A: Parser](n: Int)(implicit builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}

object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

class OutputWriter(out: PrintWriter) extends AutoCloseable {
  def this(out: OutputStream) = this(new PrintWriter(out))

  var separator = " "
  private[this] var isNewLine: Boolean = true

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

  def newLine(): this.type = {
    isNewLine = true
    out.println()
    this
  }

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj

  override def close() = {
    out.flush()
    out.close()
  }
}

/**
 * Created by aborisenko on 21.02.16.
 */

import io.StdIn._

object Main extends App {
  def b651 (){

    val n = readInt()

    val a = readLine().split(" ").map(_.toInt)

    var b = Array.fill[Int](1001)(0)

    for(i <- 0 to n-1) {
      b(a(i)) += 1
    }

    var result = 0

    var nn = 0
    var f = true

    while(f){
      f = false
      for(j <- 1 to 1000){
        if( b(j) > 0 ) {
          result += 1
          b(j) -= 1
          f = true
        }
      }
      if( f )  result -= 1
    }

    println( result )
  }

  b651()
}

// 1 1 2 2 3 3

// 1 2 3 1 2 3

// 1 2 1 2 3 3

/**
 * Created by aborisenko on 21.02.16.
 */

import io.StdIn._

object Main extends App {
  def b651 (){

    val n = readInt()

    val a = readLine().split(" ").map(_.toInt)

    var b = Array.fill[Int](1001)(0)

    for(i <- 0 to n-1) {
      b(a(i)) += 1
    }

    var result = 0

    var i = 1
    while( b(i) == 0)
      i += 1

    var nn = b(i)

    for(j <- i+1 to 1000){
      if(b(j) > 0) {
        result += Math.min(nn, b(j))
        nn = Math.abs(nn - b(j)) + 1
      }
    }

    println(result)
  }

  b651()
}


object CF939A extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val f = Seq.fill[Int](n)(sc.nextInt)
  val fn = (1 to n) map (i => f(i-1)) map (i => f(i-1)) map (i => f(i-1)) map (_ - 1)
  println(if ((fn zipWithIndex) filter (a => a._1 == a._2) nonEmpty) "YES" else "NO")
}

object LoveTriangle {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val n= in.readInt()
    val arr=in.readLine().split(" ").map(_.toInt-1)
    for(i<- 0 until n){
      var j=i
      val visited=Array.fill[Boolean](n)(false)
      var loopSize=0
      while (!visited(j)){
        visited(j)=true
        j=arr(j)
        loopSize+=1
      }
      if(j==i && loopSize==3){
        println("YES")
        return
      }
    }
    println("NO")
  }
}

import scala.collection.mutable.HashSet

//https://codeforces.com/problemset/problem/939/A
object LoveTriangle {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val n= in.readInt()
    val arr=in.readLine().split(" ").map(_.toInt-1)
    for(i<- 0 until n){
      var j=i
      //val visited=Array.fill[Boolean](n)(false)
      val visited=HashSet[Int]()
      var loopSize=0
      while (!visited.contains(j)){
        visited+=(j)
        j=arr(j)
        loopSize+=1
      }
      if(j==i && loopSize==3){
        println("YES")
        return
      }
    }
    println("NO")
  }
}

object A464 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    val n = readInt
    val arr = readInts(n)
    val res = arr.exists { a =>
      val c = arr(arr(a - 1) - 1)
      a != c && arr(c - 1) == a
    }
    out.println(if (res) "YES" else "NO")
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object LoveTriangle939A_v2   extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val nodes = (0 until n).map(Node).toArray
    val edges = (0 until n).map(i => Edge(nodes(i), nodes(scanner.nextInt()-1)))

    val g = new Graph(nodes,edges)

    val existsLoveTriangle: Boolean = g.existsCycleOf3()

    if(existsLoveTriangle)
      out.println("YES")
    else
      out.println("NO")
  }
}
class Graph(val nodes: Seq[Node],val edges: Seq[Edge]){
  val edgesOutgoing = nodes.map(n => n -> edges.filter(_.from == n)).toMap
  def existsCycleOf3(): Boolean = {
    nodes.foreach(_.visited = false)
    nodes.foreach(_.cleared = false)

    def dfs(u: Node): Boolean = {
      u.visited=true
      val result = edgesOutgoing(u).exists{ e =>
        val v = e.to
        if(v.cleared){
          false
        }else {
          if (v.visited) {
            u.indexDFS == v.indexDFS + 2
          } else {
            v.indexDFS = u.indexDFS + 1
            dfs(v)
          }
        }
      }

      u.cleared = true
      result
    }
    nodes.exists{ u =>
      if(u.visited) false
      else{
        u.indexDFS = 0
        dfs(u)
      }
    }
  }
}
case class Node(node: Int){
  var visited: Boolean = false
  var indexDFS: Int = 0
  var cleared: Boolean = false

}
case class Edge(from: Node, to: Node)

object LoveTriangle939A  extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val f = (0 until n).map(_ => scanner.nextInt()-1)

    val existsLoveTriangle = (0 until n).exists{ a =>
      val b = f(a)
      val c = f(b)
      f(c) == a
    }
    if(existsLoveTriangle)
      out.println("YES")
    else
      out.println("NO")
  }
}

object A464 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    out.println(sys.env)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (sys.env.contains("ONLINE_JUDGE")) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object A464 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    val n = readInt
    val arr = readInts(n)
    val res = arr.exists { a =>
      val b = arr(a - 1)
      val c = arr(b - 1)
      a != c && c == a
    }
    out.println(if (res) "YES" else "NO")
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object LoveTriangle939A_v2 extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val nodes = (0 until n).map(Node).toArray
    val edges = (0 until n).map(i => Edge(nodes(i), nodes(scanner.nextInt()-1)))

    val g = new Graph(nodes,edges)

    val existsLoveTriangle: Boolean = g.existsCycleOf3()

    if(existsLoveTriangle)
      out.println("YES")
    else
      out.println("NO")
  }
}
class Graph(val nodes: Seq[Node],val edges: Seq[Edge]){
  val edgesOutgoing = nodes.map(n => n -> edges.filter(_.from == n)).toMap
  def existsCycleOf3(): Boolean = {
    nodes.foreach(_.visited = false)
    nodes.foreach(_.indexDFS = 0)
    def dfs(u: Node): Boolean = {
      u.visited=true
      edgesOutgoing(u).exists{ e =>
        val v = e.to
        if(v.visited){
          u.indexDFS == v.indexDFS+2
        }else{
          v.indexDFS = u.indexDFS+1
          dfs(v)
        }
      }

    }
    nodes.exists{ u =>
      if(u.visited) false
      else{
        dfs(u)
      }
    }
  }
}
case class Node(node: Int){
  var visited: Boolean = false
  var indexDFS: Int = 0

}
case class Edge(from: Node, to: Node)

object LoveTriangle939A_v2 extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val nodes = (0 until n).map(Node).toArray
    val edges = (0 until n).map(i => Edge(nodes(i), nodes(scanner.nextInt()-1)))

    val g = new Graph(nodes,edges)

    val existsLoveTriangle: Boolean = g.existsCycleOf3()

    if(existsLoveTriangle)
      out.println("YES")
    else
      out.println("NO")
  }
}
class Graph(val nodes: Seq[Node],val edges: Seq[Edge]){
  val edgesOutgoing = nodes.map(n => n -> edges.filter(_.from == n)).toMap
  def existsCycleOf3(): Boolean = {
    nodes.foreach(_.visited = false)

    def dfs(u: Node): Boolean = {
      u.visited=true
      edgesOutgoing(u).exists{ e =>
        val v = e.to
        if(v.visited){
          u.indexDFS == v.indexDFS+2
        }else{
          v.indexDFS = u.indexDFS+1
          dfs(v)
        }
      }

    }
    nodes.exists{ u =>
      if(u.visited) false
      else{
        u.indexDFS = 0
        dfs(u)
      }
    }
  }
}
case class Node(node: Int){
  var visited: Boolean = false
  var indexDFS: Int = 0

}
case class Edge(from: Node, to: Node)


import java.io._
import java.util.StringTokenizer
import java.lang.Long
import scala.collection.immutable.HashSet

/**
 * @author kperikov
 */
object D_334 {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def solve = {
    val n = nextInt
    val m = nextInt
    var setX = new HashSet[Int]()
    var setY = new HashSet[Int]()
    for (i <- 0 until m) {
      setX += nextInt
      setY += nextInt
    }
    var ans = 0
    for (i <- 2 to n - 1) {
      if (!setX.contains(i)) {
        ans += 1
      }
      if (!setY.contains(i)) {
        ans += 1
      }
    }
    if (n % 2 == 1 && !setX.contains(n / 2) && !setY.contains(n / 2) && ans > 1) {
      ans -= 1
    }
    out.println(ans)
  }
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(c, r) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  val useCol = Array.fill(n)(false)
  for (i <- badCols.indices) {
  	useCol(i) = !badCols(i)// && !(!badRows(i) && !badRows(n - i - 1) && useCol(n - i - 1))
  }

  val res = useCol.count(identity) + badRows.indices.count(i => !badRows(i) && ((i != n / 2 || n % 2 != 1) || !useCol(i) || !useCol(n - i - 1)))

  println(res)
}

import scala.collection.mutable

/**
 * User: Oleg Nizhnik
 * Date: 29.07.13
 * Time: 20:30
 */
object D_Chips extends App {
  def readPair() = readLine() split ' ' map (_.toInt)
  val xs, ys = mutable.BitSet.empty
  val Array(n, m) = readPair()
  2 to (n - 1) foreach (i => xs.add(i) && ys.add(i))
  1 to m foreach (_ => readPair() match {case Array(x, y) => xs.remove(x); ys.remove(y)})
  println(xs.size + ys.size -
    (if (n % 2 == 1 && xs.contains((n + 1) / 2) && ys.contains((n + 1) / 2)) 1 else 0))

}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(c, r) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  val mid = n / 2
  if (n % 2 == 1 && !badCols(mid)) badRows(mid) = true

  println(badCols.count(!_) + badRows.count(!_))
}

/**
 * User: Oleg Nizhnik
 * Date: 29.07.13
 * Time: 20:30
 */
object D_Chips extends App {
  def readPair() = readLine() split ' ' map (_.toInt)
  val Array(n, m) = readPair()
  val (xr, yr) = 1 to m map (_ => readPair()) unzip {case Array(x, y) => (x, y)}
  println((2 to (n - 1) diff xr).size + (2 to (n - 1) diff yr).size - (if (n % 2 == 1 && !xr.contains((n + 1 / 2)) && !yr.contains((n + 1) / 2)) 1 else 0))

}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(r, c) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)

  val res = badCols.count(!_) + badRows.count(!_)

  println(res)
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(c, r) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)

  val res = badCols.count(!_) + badRows.count(!_)

  println(res)
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  var i = 0
//  var rc = (0, 0)

  while (i < m) {
    //val Array(c, r) = readInts
    val rc = Console.readf2("{0,number} {1,number}")
    badCols(rc._1.asInstanceOf[Long].toInt - 1) = true
    badRows(rc._2.asInstanceOf[Long].toInt - 1) = true
    i += 1
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  //badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)

  val res = badCols.count(!_) max badRows.count(!_)

  println(res)
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(c, r) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  val useCol = Array.fill(n)(false)
  for (i <- badCols.indices) {
  	useCol(i) = !badCols(i)// && !(!badRows(i) && !badRows(n - i - 1) && useCol(n - i - 1))
  }

  val res = useCol.count(identity) + badRows.indices.count(i => !badRows(i))// && (!useCol(i) || !useCol(n - i - 1)))

  println(res)
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(c, r) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  val res = badCols.count(!_) + badRows.indices.count(i => !badRows(i) && (badCols(i) || badCols(n - i - 1)))

  println(res)
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  var i = 0
//  var rc = (0, 0)

  while (i < m) {
    //val Array(c, r) = readInts
    val rc = Console.readf2("{0,number} {1,number}")
    badCols(rc._1.asInstanceOf[Long].toInt - 1) = true
    badRows(rc._2.asInstanceOf[Long].toInt - 1) = true
    i += 1
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  badCols.indices.filter(i => !badCols(i)).foreach(i => badRows(i) = true)

  val res = badCols.count(!_) + badRows.count(!_)

  println(res)
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(c, r) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  val useCol = Array.fill(n)(false)
  for (i <- badCols.indices) {
  	useCol(i) = !badCols(i) && !(!badRows(i) && !badRows(n - i - 1) && useCol(n - i - 1))
  }

  val res = useCol.count(identity) + badRows.indices.count(i => !badRows(i) && (!useCol(i) || !useCol(n - i - 1)))

  println(res)
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val badCols = Array.fill(n)(false)
  val badRows = Array.fill(n)(false)

  for (i <- 0 until m) {
    val Array(c, r) = readInts
    badCols(c - 1) = true
    badRows(r - 1) = true
  }

  badCols(0) = true
  badCols(n - 1) = true
  badRows(0) = true
  badRows(n - 1) = true

  val res = badCols.count(!_) + badRows.indices.count(i => !badRows(i) && (badCols(i) || badCols(n - i)))

  println(res)
}


import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int, val c: Long)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val s = readString()
        val arr = new Array[Int](1000)
        for (c <- s) {
            arr(c.toInt) += 1
        }
        for (i <- 0 until 1000) {
            if (arr(i) == 2){
                writer.print(i.toChar)
            }
        }
        for (i <- 0 until 1000) {
            if (arr(i) == 2){
                writer.print(i.toChar)
            }
        }
        for (i <- 0 until 1000) {
            if (arr(i) == 1){
                writer.print(i.toChar)
            }
        }
        writer.println()

        def check(kk: Long): Boolean = {
            return true
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}

import scala.io.StdIn.readLine

object Letters {
  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 0 until t) {
      println(readLine().sorted)
    }
  }
}


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

object Codeforces1163B {

  def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {
    val isStreak = new Array[Boolean](n)
    val colorFrequencyMap = new mutable.HashMap[Int, Int]()
    val countTracker = new FrequencyCountTracker
    for (i <- 0 until n) {
      val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)
      colorFrequencyMap(u(i)) = previousFrequency + 1

      countTracker.decreaseCount(previousFrequency)
      countTracker.increaseCount(previousFrequency + 1)

      isStreak(i) = countTracker.isEqualFrequencyByRemovingOne
    }
    for (i <- isStreak.indices.reverse) {
      if (isStreak(i)) return i + 1
    }
    1
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val u = StdIn.readLine().trim.split(" ").map(_.toInt)
    val longestPossibleStreak = getLongestPossibleStreak(n, u)
    println(longestPossibleStreak)
  }

  class FrequencyCountTracker {
    val frequencyCountMap = new mutable.HashMap[Int, Int]()

    def increaseCount(frequency: Int): Unit = {
      val previousFrequencyCount = frequencyCountMap.getOrElse(frequency, 0)
      frequencyCountMap(frequency) = previousFrequencyCount + 1
    }

    def decreaseCount(frequency: Int): Unit = {
      if (frequency == 0) return
      val previousFrequencyCount = frequencyCountMap(frequency)
      previousFrequencyCount match {
        case 1 => frequencyCountMap.remove(frequency)
        case _ => frequencyCountMap(frequency) = previousFrequencyCount - 1
      }
    }

    def isEqualFrequencyByRemovingOne: Boolean = {
      frequencyCountMap.keys.size match {
        case 1 =>
          frequencyCountMap.keys.head == 1 || frequencyCountMap.values.head == 1
        case 2 =>
          val maxFrequency = frequencyCountMap.keys.max
          val minFrequency = frequencyCountMap.keys.min
          if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true
          else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true
          else false
        case _ =>
          false
      }
    }
  }

}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](10)
    var ans = 0

    def test: Boolean = {
      map(10) { i =>
        if (C(i) > 0) {
          C(i) -= 1

          var num = 0
          var ok = true
          REP(10) { j =>
            if (C(j) != 0) {
              if (num != 0 && num != C(j)) {
                ok = false
              } else {
                num = C(j)
              }
            }
          }

          C(i) += 1
          ok
        } else {
          false
        }
      }.exists(identity)
    }

    REP(N) { i =>
      val u = ni() - 1
      C(u) += 1

      debug(C)
      if (test) ans = i + 1
    }

    out.println(ans)
  }
}

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

  override def apply(io: IO): io.type = {
    val nums = io.read[Vector[Int]]

    val numToCount, countToMap = mutable.Map.empty[Int, Int].withDefaultValue(0)
    val ans = nums map {i =>
      val curr = numToCount(i)
      if (curr > 0) {
        countToMap(curr) -= 1
        if (countToMap(curr) <= 0) countToMap.remove(curr)
      }
      numToCount(i) = curr + 1
      countToMap(curr + 1) += 1

      val it = countToMap.keysIterator

      val res = countToMap.size match {
        case 1 =>
          val c1 = it.next()
          c1 == 1 || countToMap(c1) == 1
        case 2 =>
          val _c1, _c2 = it.next()
          val c1 = _c1 min _c2
          val c2 = _c1 max _c2

          ((c1 == 1) && countToMap(c1) == 1) ||
          (c1 == c2 - 1 && countToMap(c2) == 1)
        case _ => false
      }
      //debug(i, numToCount, countToMap, res)
      res
    }

    io.write(ans.lastIndexWhere(identity) + 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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[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 writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    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.collection.mutable
import scala.io.StdIn

object Codeforces1163B {

  def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {
    val isStreak = new Array[Boolean](n)
    val colorFrequencyMap = new mutable.HashMap[Int, Int]()
    val countTracker = new FrequencyCountTracker
    for (i <- 0 until n) {
      val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)
      colorFrequencyMap(u(i)) = previousFrequency + 1

      countTracker.decreaseCount(previousFrequency)
      countTracker.increaseCount(previousFrequency + 1)

      isStreak(i) = countTracker.isEqualFrequencyByRemovingOne
    }
    for (i <- isStreak.indices.reverse) {
      if (isStreak(i)) return i + 1
    }
    1
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val u = StdIn.readLine().trim.split(" ").map(_.toInt)
    val longestPossibleStreak = getLongestPossibleStreak(n, u)
    println(longestPossibleStreak)
  }

  class FrequencyCountTracker {
    val frequencyCountMap = new mutable.HashMap[Int, Int]()

    def increaseCount(frequency: Int): Unit = {
      val previousCount = frequencyCountMap.getOrElse(frequency, 0)
      frequencyCountMap(frequency) = previousCount + 1
    }

    def decreaseCount(frequency: Int): Unit = {
      if (frequency == 0) return
      val previousCount = frequencyCountMap(frequency)
      previousCount match {
        case 1 => frequencyCountMap.remove(frequency)
        case _ => frequencyCountMap(frequency) = previousCount - 1
      }
    }

    def isEqualFrequencyByRemovingOne: Boolean = {
      frequencyCountMap.keys.size match {
        case 1 =>
          frequencyCountMap.keys.head == 1
        case 2 =>
          val maxFrequency = frequencyCountMap.keys.max
          val minFrequency = frequencyCountMap.keys.min
          if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true
          else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true
          else false
        case _ =>
          false
      }
    }
  }

}


import scala.collection.mutable.ArrayBuffer

object C extends App {

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

  val Array(n) = readInts(1)
  val ts = readInts(n)

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int, z: Int, x: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = i != j && isValid(i) && isValid(j) && isValid(u) && isValid(v) && isValid(z) && isValid(x)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b, b, b)) res += 1
      for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a, a, a)) res += 1
    case Seq(a, b, c) =>
      if (canSwapWithCheck(a, c, b, b, b, b)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c, a, a)) res += 1
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d, a, a)) res += 1
      if (canSwapWithCheck(a, d, b, c, a, a)) res += 1
      if (canSwapWithCheck(b, c, a, d, a, a)) res += 1
      if (canSwapWithCheck(b, d, a, c, a, a)) res += 1
    case Seq(a, b, c, d, e) =>
      if (canSwapWithCheck(b, d, a, c, e, a)) res += 1
      if (canSwapWithCheck(b, e, a, c, d, a)) res += 1
      if (canSwapWithCheck(a, d, b, c, e, a)) res += 1
    case Seq(a, b, c, d, e, f) =>
      if (canSwapWithCheck(b, e, a, c, d, f)) res += 1
    case _ =>
  }

  println(res)
}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      val res = data.indices.foldLeft(0l) {
        case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
        case (sum, i) => sum
      }

      val doubles = invalid.toList.map(i => validChanges(data, invalid, i)).sum / 2
      println(res + doubles)
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      val res = data.indices.foldLeft(0l) {
        case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
        case (sum, i) => sum
      }

      val doubles = invalid.map(i => validChanges(data, invalid, i)).sum
      println(res + doubles)
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Int], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }

    val doubles = invalid.indices.count(i => validChanges(data, invalid, i) != 0) / 2
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0l) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Int], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0l) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Int], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

//import scala.io.Source
//
//object Solution extends App {
//  val in = Source.stdin.getLines()
//  val n = in.next().toInt
//  val data = in.next().split(' ').map(_.toInt)
//  val indexValue = data.indices.foldLeft(Map.empty[Int, (Int, Int)]) {
//    case (acc, i) if !acc.contains(data(i)) =>
//      acc + (data(i) -> (i, 0))
//    case (acc, i) if acc(data(i))._2 == -1 => acc
//    case (acc, i) if acc(data(i))._2 == 0 =>
//      acc + (data(i) -> (i, i - acc(data(i))._1))
//    case (acc, i) =>
//      val distance = i - acc(data(i))._1
//      acc + (data(i) -> (i, if (acc(data(i))._2 == distance) distance else - 1))
//  }
//  println(indexValue.filter(_._2._2 >= 0).keys.toList.sorted.map{case v => s"$v ${indexValue(v)._2}"}.mkString("\n"))
//
//}ё

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      println(data.indices.foldLeft(0l) {
        case (sum, i) => sum + validChanges(data, invalid, i)
      } - 1)
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      val res = data.indices.foldLeft(0l) {
        case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
        case (sum, i) => sum
      }

      val doubles = invalid.map(i => validChanges(data, invalid, i)).sum
      println(res + doubles)
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Int], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }

    val doubles = invalid.indices.map(i => validChanges(data, invalid, i)).sum / 2
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet

    val res = data.indices.foldLeft(0l) {
      case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
      case (sum, i) => sum
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum
//    println(doubles)
    println(res + doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      println(data.indices.foldLeft(0l) {
        case (sum, i) => sum + validChanges(data, invalid, i)
      })
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0l) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

import scala.collection._
import scala.collection.mutable.ArrayBuffer

object C 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) = readInts(1)
  val ts = readInts(n)

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwap(i: Int, j: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j)
    ts(i) = ti
    ts(j) = tj
    can
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j) && isValid(u) && isValid(v)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwap(a, i)) res += 1
      for (i <- ts.indices) if (i != a && canSwap(b, i)) res += 1
    case Seq(a, b, c) =>
      if (canSwap(a, c)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(a, d, b, c)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, c, a, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, d, a, c)) res += 1 //{println("a"); res += 1}
    case _ =>
  }

  println(res)
}

import scala.collection._
import scala.collection.mutable.ArrayBuffer

object C 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) = readInts(1)
  val ts = readInts(n)

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int, z: Int, x: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = i != j && isValid(i) && isValid(j) && isValid(u) && isValid(v) && isValid(z) && isValid(x)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b, b, b)) res += 1
      for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a, a, a)) res += 1
    case Seq(a, b, c) =>
      if (canSwapWithCheck(a, c, b, b, b, b)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c, a, a)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d, a, a)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(a, d, b, c, a, a)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, c, a, d, a, a)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, d, a, c, a, a)) res += 1 //{println("a"); res += 1}
    case Seq(a, b, c, d, e) =>
      if (canSwapWithCheck(b, d, a, c, e, a)) res += 1
    case Seq(a, b, c, d, e, f) =>
      if (canSwapWithCheck(b, e, a, c, d, f)) res += 1
    case _ =>
  }

  println(res)
}

import scala.collection._
import scala.collection.mutable.ArrayBuffer

object C 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) = readInts(1)
  val ts = readInts(n)

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwap(i: Int, j: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwap(a, i)) res += 1
      for (i <- ts.indices) if (i != a && canSwap(b, i)) res += 1
    case Seq(a, b, c) =>
      if (canSwap(a, c)) res += 1
      for (i <- ts.indices) if (canSwap(b, i)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwap(a, c)) res += 1 //{println("a"); res += 1}
      if (canSwap(a, d)) res += 1 //{println("a"); res += 1}
      if (canSwap(b, c)) res += 1 //{println("a"); res += 1}
      if (canSwap(b, d)) res += 1 //{println("a"); res += 1}
    case _ =>
  }

  println(res)
}

import scala.collection._
import scala.collection.mutable.ArrayBuffer

object C 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) = readInts(1)
  val ts = readInts(n)

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwap(i: Int, j: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j)
    ts(i) = ti
    ts(j) = tj
    can
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j) && isValid(u) && isValid(v)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b)) res += 1
      for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a)) res += 1
    case Seq(a, b, c) =>
      if (canSwapWithCheck(a, c, b, b)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(a, d, b, c)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, c, a, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, d, a, c)) res += 1 //{println("a"); res += 1}
    case _ =>
  }

  println(res)
}