import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val Array(n, _) = readInts
  def ans = (1 +: readInts).sliding(2).map(x => (x.last.toLong - x.head + n) % n).sum

  def main(a: Array[String]) {
    println(ans)
  }
}

import scala.io.StdIn.readLine

object Main extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val a = 1 :: readLine().split(" ").map(_.toInt).toList
  val intervals = a.zip(a.tail)
  val ans = intervals.map(cost).sum
  println(ans)

  def cost(interval: (Int, Int)): Long = {
    val (s, e) = interval
    if (s > e) (n - s + 1) + (e - 1)
    else e - s
  }
}

object cf extends App {
  import java.util.Scanner
  val in = new Scanner(System.in)

  val n, m = in.nextInt
  val a = for (i <- 1 to m) yield in.nextInt
  val res = (1 :: a.toList).sliding(2)
  .foldLeft(0L)((sum, pos) => {
    sum + ((pos(1) + n) - pos(0)) % n
  })
  println(res)
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def solve() {
		val (n,m) = (nextInt,nextInt)
		val a = for (i <- 1 to m) yield nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	val in = new BufferedReader(new InputStreamReader(System.in))
	var st = new StringTokenizer("")

	def next : String = {
		while (!st.hasMoreTokens) {
			val line = in.readLine
			if (line == null) return null
			eat(line)
		}
		st.nextToken
	}

	def eat( s : String ) = st = new StringTokenizer(s)
	def nextInt = next.toInt
	def nextLong = next.toLong
	def nextDouble = next.toDouble

	def main(args: Array[String]) {
		eat("")
		solve
	}
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def solve() {
		val n = nextInt
		val m = nextInt
		val a = for (i <- 1 to m) yield nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	val in = new BufferedReader(new InputStreamReader(System.in))
	var st = new StringTokenizer("")

	def next : String = {
		while (!st.hasMoreTokens) {
			val line = in.readLine
			if (line == null) return null
			eat(line)
		}
		st.nextToken
	}

	def eat( s : String ) = st = new StringTokenizer(s)
	def nextInt = next.toInt
	def nextLong = next.toLong
	def nextDouble = next.toDouble

	def main(args: Array[String]) {
		eat("")
		solve
	}
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def main(args: Array[String]) {
		val in = new FastReader
		//val n = in.nextInt
		//val m = in.nextInt
		val (n,m) = (in.nextInt,in.nextInt)
		val a = for (i <- 1 to m) yield in.nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	class FastReader {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def FastReader {
			eat("")
		}

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def eat( s : String ) = st = new StringTokenizer(s)
		def nextInt = next.toInt
		def nextLong = next.toLong
		def nextDouble = next.toDouble
	}

}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def main(args: Array[String]) {
		val in = new FastReader
		val n = in.nextInt
		val m = in.nextInt
		val a = for (i <- 1 to m) yield in.nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	class FastReader {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def FastReader {
			eat("")
		}

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def eat( s : String ) = st = new StringTokenizer(s)
		def nextInt = next.toInt
		def nextLong = next.toLong
		def nextDouble = next.toDouble
	}

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  println(in.next().split(" ").map(_.toInt).foldLeft((1, 0l)) {
    case((prev, count), el) if el >= prev => (el, count + (el - prev))
    case((prev, count), el) => (el, count + n - prev + el)
  }._2)
}

object B339 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val house = readInts(m)
    var curr = 1
    var res = 0L
    for(i <- 0 until m) {
      if(house(i) < curr) {
        res += n - curr + house(i)
      } else if (house(i) > curr) {
        res += house(i) - curr
      }
      curr = house(i)
    }
    println(res)
  }
}

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toLong)
  val t = StdIn.readLine().split(" ").map(_.toLong)
  val result = t.iterator.sliding(2).withPartial(false).map { x =>
    if(x.head == x(1)) 0
    else if (x.head < x(1)) x(1) - x.head
    else n - (x.head - x(1))
  }.sum + (t(0) - 1)

  println(result)

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P339B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  type Tasks = List[Long]

  val A: Tasks = List.fill(M)(sc.nextLong)

  def solve(): Unit = {

    def cost(x: Long, y: Long): Long = if (y < x) y - x + N
                                    else y - x

    @tailrec
    def loop(acc: Long, pos: Long, tasks: Tasks): Long = tasks match {
        case Nil     => acc
        case x :: xs => loop(acc + cost(pos, x), x, xs)
      }

    out.println(loop(0, 1, A))
  }

  solve
  out.close
}

object XeniaAndRingroad {
	def main (args: Array[String]) {
		//Parsing the input
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextLong;
		val m = scanner.nextLong;
		var last : Long = 1;
		var moves : Long = 0;
		for (i <- 1 to m.asInstanceOf[Int]) {
		  val current = scanner.nextLong();
		  if (current >= last)
		    moves += (current - last)
		  else
		    moves += (n - last) + current
		  last = current;
		}
		println(moves)
	}
}

object Main {
  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val m = (Array(1) ++ a).sliding(2).map { x =>
      val x1 = x(0)
      val x2 = x(1)
      if (x2 < x1) (nm(0) - x1 + x2).toLong
      else (x2 - x1).toLong
    }
    println(m.sum)
  }
}

import java.util.Scanner

import scala.io.StdIn
import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
  val in = new Scanner(System.in)
    val (n, m) = (in.nextInt, in.nextInt)
    var x = 1
    var cnt = 0l
//    val a = ofDim[Int](m + 1)
    val a = for(i <- 1 to m) yield in.nextInt
    for(i <- a){

      if(i >= x){
//        println(cnt)
        cnt += i - x
//        println(cnt)
//        x = i
      }
      else{
//        println(cnt)
        cnt += n + i - x
//        println(cnt)
      }
      x = i

    }
  println(cnt)
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

import Math.abs

object RingRoad {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val (n,m) = readTuple
     val as = readLongs
     println(as.foldLeft( (1L, 0L)){ case ( (cur: Long, dist: Long), next: Long) =>
       (next,  dist + (if (next >= cur) next-cur else n-cur+next))
     }._2)

   }

}

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)
  var a = Array.fill(m)(nextInt)

  println((1 :: a.toList).sliding(2)
    .foldLeft(0L)((sum, pos) => sum + ((pos(1) - pos(0) + n) % n) ))

  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)

  var (ans, last) = (0l, 1)
  for (_ <- 1 to m) {
    var ind = nextInt
    ans += (if (last <= ind) ind - last else n - (last - ind))
    last = ind
  }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)

  var (ans, last) = (0l, 1)
  var a = for (_ <- 1 to m) yield {
    var ind = nextInt
    ans += (ind + n - last) % n
    last = ind
    ind
  }

  val res = (1 :: a.toList).sliding(2)
  .foldLeft(0L)((sum, pos) => {
    sum + ((pos(1) + n) - pos(0)) % n
  })
  //res.foreach { x => Console.err.println(x) }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object Solution extends App {
  val Array(n, m) = readLine.split(" ").map(_.toLong)
  val as = readLine.split(" ").map(_.toLong)

  val ups = as.foldLeft((0l, 1l)){ case(p, c) =>
    if(p._1 > c) {
      (c, p._2 + 1)
    } else {
      (c, p._2)
    }
  }

  println((ups._2-1)*n + (as.last - 1))
}

object cf extends App {
  import java.util.Scanner
  val in = new Scanner(System.in)

  val n, m = in.nextInt
  val a = for (i <- 1 to m) yield in.nextInt
  val res = (1 :: a.toList).sliding(2)
  .foldLeft(0)((sum, pos) => {
    sum + ((pos(1) + n) - pos(0)) % n
  })
  println(res)
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def solve() {
		val n = nextInt
		val m = nextInt
		val a = for (i <- 1 to m) yield nextInt

		var cur = 1
		var ans = 0
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	val in = new BufferedReader(new InputStreamReader(System.in))
	var st = new StringTokenizer("")

	def next : String = {
		while (!st.hasMoreTokens) {
			val line = in.readLine
			if (line == null) return null
			eat(line)
		}
		st.nextToken
	}

	def eat( s : String ) = st = new StringTokenizer(s)
	def nextInt = next.toInt
	def nextLong = next.toLong
	def nextDouble = next.toDouble

	def main(args: Array[String]) {
		eat("")
		solve
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  println(in.next().split(" ").map(_.toInt).foldLeft((1, 0)) {
    case((prev, count), el) if el >= prev => (el, count + (el - prev))
    case((prev, count), el) => (el, count + n - prev + el)
  }._2)
}

object B339 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val house = readInts(m)
    var curr = 1
    var res = 0
    for(i <- 0 until m) {
      if(house(i) < curr) {
        res += n - curr + house(i)
      } else if (house(i) > curr) {
        res += house(i) - curr
      }
      curr = house(i)
    }
    println(res)
  }
}

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
  val t = StdIn.readLine().split(" ").map(_.toInt)
  val result = t.sliding(2).map { x =>
    if(x(0) == x(1)) 0
    else if (x(0) < x(1)) x(1) - x(0)
    else n - (x(0) - x(1))
  }.sum + (t(0) - 1)

  println(result)

}

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
  val t = StdIn.readLine().split(" ").map(_.toInt)

  val result = t.sliding(2).map { x =>
    if(x(0) == x(1)) 0
    else if (x(0) < x(1)) x(1) - x(0)
    else x(0) - x(1) + n - 2
  }.sum + (t(0) - 1)

  println(result)

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P339B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  type Tasks = List[Int]

  val A: Tasks = List.fill(M)(sc.nextInt)

  def solve(): Unit = {

    @tailrec
    def loop(acc: Int, pos: Int, tasks: Tasks): Int = tasks match {
        case Nil     => acc
        case x :: xs => {
          val cost = x - pos
          if (cost < 0) loop(acc + cost + N, x, xs)
          else loop(acc + cost, x, xs)
        }
      }

    out.println(loop(0, 1, A))
  }

  solve
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val Array(n, _) = readInts
  def ans = (1 +: readInts).sliding(2).map(x => (x.last - x.head + n) % n).sum

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val m = (Array(1) ++ a).sliding(2).map { x =>
      val x1 = x(0)
      val x2 = x(1)
      if (x2 < x1) nm(0) - x1 + x2
      else x2 - x1
    }
    println(m.sum)
  }
}

import scala.io.StdIn
import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
    var x = 1
    var cnt = 0
    for(i <- 1 to m){
      if(x < i & x != i){
        cnt += x - i
        x = i
        println(cnt)
      }
      if(x > i & x != i){
        cnt += n - i + x
        x = i
      }
    }
  println(Math.abs(cnt))
  }
}

 import java.util.Scanner

import scala.io.StdIn
import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
  val in = new Scanner(System.in)
    val (n, m) = (in.nextInt, in.nextInt)
    var x = 1
    var cnt = 0
//    val a = ofDim[Int](m + 1)
    val a = for(i <- 1 to m) yield in.nextInt
    for(i <- a){

      if(i >= x){
//        println(cnt)
        cnt += i - x
//        println(cnt)
//        x = i
      }
      else{
//        println(cnt)
        cnt += n + i - x
//        println(cnt)
      }
      x = i

    }
  println(cnt)
  }
}

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)
  var a = Array.fill(n)(nextInt)

  println((1 :: a.toList).sliding(2)
    .foldLeft(0L)((sum, pos) => sum + ((pos(1) + n) - pos(0)) % n ))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object Solution extends App {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val as = readLine.split(" ").map(_.toInt)

  val ups = as.foldLeft((0, 1)){ case(p, c) =>
    if(p._1 > c) {
      (c, p._2 + 1)
    } else {
      (c, p._2)
    }
  }

  println((ups._2-1)*n + (as.last - 1))
}


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 l: Int, val r: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (r-l).compareTo(that.r-that.l)
        }
    }

    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 mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+1)
        for (i <- 1 to n) {
            arr(i) = readInt()
        }
        writer.println(bs(1, 1000000000))
        def check(kk: Long): Boolean = {
            val b = new Array[Int](n+1)
            for (i <- (3 to n).reverse) {
                if (arr(i) + b(i) < kk)
                    return false
                val d = (min(arr(i) + b(i) - kk, arr(i)) / 3).toInt
                b(i-1) += d
                b(i-2) += 2*d
            }
            if (arr(2) + b(2) < kk)
                return false
            if (arr(1) + b(1) < kk)
                return false
            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 java.util

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val hs = nextLongs(n)
      val add = Array.fill(n)(0L)

      def can(lim: Long): Boolean = {
        util.Arrays.fill(add, 0)
        var i = n - 1
        var ok = true
        while (i > 1) {
          val avail = Math.min(hs(i), hs(i) + add(i) - lim)
          val d = avail / 3
          if (d > 0) {
            add(i - 1) += d
            add(i - 2) += d * 2
            add(i) -= d * 3
          }
          i -= 1
        }
        i = 0
        while (i < n) {
          if (hs(i) + add(i) < lim) {
            ok = false
            i = n
          }
          i += 1
        }
//        val tot = hs.indices.map(i => hs(i) + add(i))
//        println(lim, tot.mkString(" "))
        ok
      }

      @annotation.tailrec
      def binSearch(low: Long, hi: Long): Long = {
        if (hi < low) low
        else {
          val mid = (low + hi) / 2
          if (can(mid)) binSearch(mid + 1, hi)
          else binSearch(low, mid - 1)
        }
      }

//      println(can(8))
//      println(can(7))
//      println(can(6))

      val res = binSearch(0, hs.max + 1)

      out.println(res - 1)
    }

    out.flush()
  }

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


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

// values always get less after operation, so just and all of numbers
object Solution {
  def solve(input: Array[Int]): Int =
    input.fold(input(0)) { (v1, v2) => v1 & v2 }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val n = input.nextInt()
    val nums = (1 to n).map(_ => input.nextInt()).toArray
    output.println(solve(nums))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readArrayInt()
        var rs = a(0)
        for (i <- 1 until n)
            rs &= a(i)

        writer.println(rs)
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}

import scala.io.StdIn

object Problem extends App {
  def start() = {
    println(parseInput().map(testCase => minMaxValue(testCase)).mkString("\n"))
  }

  def arrayOp(array: Array[Int], l: Int, r: Int): Array[Int] = {
    for( i <- 0.to(r-l)) {
      array(l+i) = array(l+i) & array(r-i)
    }
    array
  }

  def minMaxValue(given: Array[Int]): Int = {
    given.foldLeft(Int.MaxValue)(_ & _)
  }

  def parseInput(): Array[Array[Int]] = {
    val testCases: Int = StdIn.readLine().stripLineEnd.trim.toInt
    var input = Array[Array[Int]]()
    for (_ <- 0L.until(testCases)) {
      val n = StdIn.readLine().stripLineEnd.trim.toInt
      val testCase = StdIn.readLine().split(" ").map(_.stripLineEnd.trim.toInt)
      input = input ++ Array(testCase)
    }
    input
  }

  start()
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans = an.tail.foldLeft(an.head)(_ & _)

    println(ans)
  }
}

import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readArrayInt()
        writer.println(a.min)

    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}


import scala.io.StdIn

object AlphabeticRemovals {
  def main(args: Array[String]): Unit = {
    val k = StdIn.readLine().split(" ")(1).toInt
    val input = StdIn.readLine()
    println(solve(input, k))
  }

  def solve(input: String, k: Int): String = {
    if (k >= input.length) return ""

    val charCount = input.groupBy(identity).mapValues(_.length)
    val alphabet = charCount.keys.toSeq.sorted

    val result = calculate(Seq.empty, alphabet, k, charCount)
    val kill = result._1
    val keep = result._2
    val decide = result._3
    var remove = result._4

    input.filterNot(c => kill.contains(c) || (c == decide
      && {remove -= 1; remove >= 0}))
  }

  private def calculate(kill: Seq[Char], keep: Seq[Char], k:Int, map: Map[Char, Int]) : (Seq[Char], Seq[Char], Char, Int) = {
    val next: Char = keep.head
    val occurs: Int = map(next)

    if (occurs > k) {
      (kill, keep.tail, next, k)
    } else {
      calculate(kill :+ next, keep.tail, k - occurs, map)
    }
  }
}

object CF_490_3_C {

  type In  = (Int, Int, String)
  type Out = String
  type SC = Seq[Char]

  def solve(in: In): Out = {
    val (n, k, s) = in
    val removals = s.toSeq.sorted.take(k)
    s.diff(removals)
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, {i.nextLine; i.nextLine})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object C999A {

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

  def main(args: Array[String]): Unit = {
    var Array(n, k) = readInts(2)
    val str = read
    val marked = Array.fill(n)(0)
    var char = 'a'
    while(k > 0 && char <= 'z') {
      for(i <- 0 until n if k > 0) {
        if(str(i) == char && marked(i) == 0) {
          marked(i) = 1
          k -= 1
        }
      }
      char = (char.toInt + 1).toChar
    }
    for(i <- 0 until n) if(marked(i) == 0)
      out.print(str(i))
    out.println("")
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val n = in.nextInt
  var k = in.nextInt
  var s = in.next
  var cnt = s.groupBy(ch => ch).mapValues(_.length)
  for (ch <- 'a' to 'z') {
    val x = cnt.getOrElse(ch, 0)
    val c = x min k
    cnt += ch -> c
    k -= c
  }

  s foreach { ch =>
    val x = cnt getOrElse(ch, 0)
    if (x == 0) out.print(ch)
    else cnt += ch -> (x - 1)
  }

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    def nextDouble: Double = next.toDouble

    def nextLine: String = br.readLine
  }

}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val set = Set('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')
  if (str == str.reverse && str.forall(set))
    println("YES")
  else
    println("NO")
}

/**
 * Created by infm on 4/24/14.
 */
object Main {
  val in = {
    val lines = {
      scala.io.Source.stdin.getLines().buffered
    }
    lines map (_ split ' ') filter (_.nonEmpty) flatten
  }

  def main(args: Array[String]){
    val mirrored = "AHIMOTUVWXY"
    val current = in.next
    if (current == current.reverse && current.forall(mirrored.contains(_)))
      println("YES")
    else
      println("NO")
  }
}

/**
 * Created by infm on 4/24/14.
 */
object A {
  val in = {
    val lines = {
      scala.io.Source.stdin.getLines().buffered
    }
    lines map (_ split ' ') filter (_.nonEmpty) flatten
  }

  def main(args: Array[String]){
    val mirrored = "AHIMOTUVWXY"
    val current = in.next
    if (current == current.reverse && current.forall(mirrored.contains(_)))
      println("YES")
    else
      println("NO")
  }
}

object Main {
  def main(args: Array[String]) {
    val name = readLine()
    val goodChars = Set[Char]('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')
    for (i <- 0 to name.length / 2) {
      if (name(i) != name(name.length - 1 - i) || !goodChars.contains(name(i))) {
        println("NO")
        return
      }
    }
    println("YES")
  }
}

object Main {

	val in = {
		val lines = {
			scala.io.Source.stdin.getLines.buffered
			//val bf = new BufferedReader(new InputStreamReader(System.in))
			//Iterator.continually(readLine)
			//Iterator.continually(bf.readLine)
		}
		lines map (_ split ' ') filter (_.nonEmpty) flatten
	}

	//val out = new PrintWriter(System.out)

	def nextInt = in.next().toInt
	def nextLong = in.next().toLong

	def main(args: Array[String]): Unit = {

		val mirror = "AHIMOTUVWXY"

		val name = in.next

		if (name == name.reverse && name.forall(mirror.contains(_)))
			println("YES")
		else
			println("NO")

	}

}

/**
 * Created by yangchaozhong on 3/12/15.
 */
object CF420A extends App {
  import scala.collection.immutable.HashSet
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val name = nextString
    val chars = HashSet('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')
    val len = name.length
    val half = len / 2
    val sum = (0 to (half - 1)).map(i => Math.abs(name(i) - name(len - 1 - i))).sum
    val count = name.count(!chars.contains(_))
    if (sum == 0 && count == 0)
      out.println("YES")
    else
      out.println("NO")
  }

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

/**
 * Created by yangchaozhong on 3/12/15.
 */
object CF420A extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val name = nextString
    if (name.length <= 1)
      out.println("NO")
    else {
      val len = name.length
      val half = len / 2
      val sum = (0 to (half - 1)).map(i => Math.abs(name(i) - name(len - 1 - i))).sum
      if (sum == 0)
        out.println("YES")
      else
        out.println("NO")
    }
  }

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


object recruits extends App {
	val (n, evts) = (readLine.toInt, readLine.split(' ').map(_.toInt))
	var (cnt, ans) = (0, 0)
	for (evt <- evts) {
		if (cnt == 0 && evt == -1) {
			ans += 1
		}
		else {
			cnt += evt
		}
	}
	print(ans)
}

import java.util.Scanner

object practice {

  def main(args: Array[String]): Unit = {
    val scan = new Scanner(System.in)
    var str = scan.next
    var crimes = 0
    var polices = 0
    var in = 0
    for (i <- 1 to str.toInt) {
      in = scan.next.toInt
      if (in == -1) {
        if (polices <= 0) {
          crimes += 1
        } else {
          polices -= 1
        }
      } else {
        polices += in
      }

    }

    println(crimes)
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var n = in.next().toInt
  println(in.next().split(" ").map(_.toInt).foldLeft((0, 0)){
    case((count, pol), -1) if pol > 0 => (count, pol - 1)
    case((count, pol), -1) => (count + 1, 0)
    case((count, pol), el) => (count, pol + el)
  }._1)
}

object A {

  def main(args: Array[String]): Unit = {
    var n = readInt
//    var a = new Array[Int](n)
//    for (i <- 0 to n-1){
//      a(i) = readInt
//    }
    var a = readLine.split(" ").map(_.toInt)
    var cnt = 0
    var ans = 0
    for (i <- 0 to a.length-1){
         if (a(i) == -1) {
        	   if (cnt > 0){
        	     cnt = cnt -1
        	   }else
        		 ans = ans + 1
         }else cnt = cnt + a(i)
    }
    println(ans)
  }

}

object A427 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    var officers = 0
    var res = 0
    for(i <- 0 until n) {
      if(input(i) == -1) {
        if(officers > 0)
          officers -= 1
        else
          res += 1
      } else {
        officers += input(i)
      }
    }
    println(res)
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P427A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Long = {
    val N = sc.nextInt

    @tailrec
    def loop(acc: Int, police: Int, i: Int): Int =  {
      if (i == N) acc
      else {
        val event = sc.nextInt
        if (event < 0) {
          if (police > 0) loop(acc, police - 1, i + 1)
          else loop(acc + 1, 0, i + 1)
        }
        else loop(acc, police + event, i + 1)
      }
    }

    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

object A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Int = {
    val N = sc.nextInt

    @tailrec
    def loop(acc: Int, police: Int, n: Int): Int = {
      if (n == N) acc
      else {
        val x = sc.nextInt
        if (x < 0) { // crime occured
          if (police > 0) { // at least one police officer
            loop(acc, police - 1, n + 1)
          }
          else {
            loop(acc + 1, 0, n + 1)
          }
        }
        else {
          loop(acc, police + x, n + 1)
        }
      }
    }
    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-17.
 */
object A427 extends App{
  val sc = new Scanner(System.in)
  var n = sc.nextInt()
  var policeNum = 0
  var untreated = 0

  while (n > 0) {
    var a = sc.nextInt()

    if (a == -1) {
      if (policeNum > 0) {
        policeNum -= 1
      } else {
        untreated += 1
      }
    } else {
      policeNum += a
    }

    n -= 1
  }

  println(untreated)
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object PoliceRecruits {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val n = readInt
     val events = readInts
     val sim = events.foldLeft( (0,0)){
       case ((crimes,pol),e) =>
         if (e > 0) (crimes,pol+e)
         else if (pol >= 1) (crimes,pol-1) else (crimes+1,pol)
     }
     println(sim._1)
   }

}

// http://codeforces.com/contest/427/problem/A
object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val ev = Array.fill(n)(sc.nextInt())
  var unrated, hired = 0;
  for (t <- ev) {
    if (t == -1) {
      if (hired == 0) unrated += 1
      else hired -= 1
    }
    else {
      hired += t
    }
  }
  println(unrated);
}

object main extends App with fastIO {

  val n = nextInt

  var (ans, cnt) = (0, 0)
  for (i <- 1 to n) {
    nextInt match {
      case -1 if cnt == 0 => ans += 1
      case n => cnt += n
    }
  }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

import util.control.Breaks._
import scala.collection.mutable.ArrayBuffer

object main extends App with fastIO {

  val n = nextInt

  var (ans, cnt) = (0, 0)
  for (i <- 1 to n) {
    nextInt match {
      case -1 => { ans += -cnt + 1 max 0; cnt = cnt - 1 max 0 }
      case n => cnt += n
    }
  }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
//  val sc = new Scanner( new FileInputStream("src/input.txt") )
  val n = sc.nextInt

    var i = 0
    var res = 0
    def cup(up: Int) = {
      i += up
      if(i<0){
        res += 1
        i = 0
      }
      (i,res)
    }

  (0 until n).foreach( i=> {
    val t = sc.nextInt
    cup(t)
  })
  println(res)
}

import java.util.Scanner

object practice {

  def main(args: Array[String]): Unit = {
    val scan = new Scanner(System.in)
    var str = scan.next
    var crimes = 0
    var polices = 0
    var in = 0
    for (i <- 1 to str.toInt) {
      in = scan.next.toInt
      if (in == -1) {
        if (polices <= 0) {
          crimes += 1
        } else {
          polices -= 1
        }
      } else {
        polices += in
      }
      if (polices > 10) {
        polices = 10
      }

    }

    println(crimes)
  }

}


import scala.collection._
import scala.util.Random
import java.util.Arrays

object B extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n).sorted.distinct
  //val as = Array.fill(n)(Random.nextInt(1000000)).sorted
  val max = as.last

  var res = 0

  for (i <- as.indices) {
    val a = as(i)
    var x = a
    var prevJ = i
    while (x <= max) {
      x += a
      val j0 = Arrays.binarySearch(as, prevJ + 1, as.length, x)
      val j = if (j0 < 0) -j0 - 2 else j0 - 1
      if (j >= 0 && as(j) > a) res = res max (as(j) - x + a)
      prevJ = j
    }
  }

  println(res)
}

import java.util.Arrays

object B extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n).sorted.distinct
  val max = as.last

  var res = 0

  for (i <- as.indices) {
    val a = as(i)
    var x = a
    var prevJ = i
    while (x <= max) {
      x += a
      val j0 = Arrays.binarySearch(as, prevJ + 1, as.length, x)
      val j = if (j0 < 0) -j0 - 2 else j0 - 1
      if (j >= 0 && as(j) > a) res = res max (as(j) - x + a)
      prevJ = j
    }
  }

  println(res)
}


object D 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 cs = readInts(n)
  val as = readInts(n).map(_ - 1)

  val visited = Array.fill(n){ false }
  val isCycle = Array.fill(n){ false }
  var num = 0
  val nums = Array.fill(n){ 0 }

  def dfs1(u: Int): Int = {
    if (visited(u)) {
      if (nums(u) > 0) nums(u)
      else {
        isCycle(u) = true
        num += 1
        nums(u) = num
        num
      }
    } else {
      visited(u) = true
      nums(u) = dfs1(as(u))
      nums(u)
    }
  }

  var i = 0
  while (i < n) {
    dfs1(i)
    i += 1
  }

  def dfs2(u: Int, start: Int, min: Int): Int = {
    val v = as(u)
    if (v == start) min
    else dfs2(v, start, min min cs(v))
  }

  i = 0
  var res = 0L
  while (i < n) {
    if (isCycle(i)) res += dfs2(i, i, cs(i))
    i += 1
  }

  println(res)
}

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val C = map(N)(_ => sc.nextInt())
    val E = map(N)(_ => sc.nextInt() - 1)
    val visited, computed = Array.ofDim[Boolean](N)

    def findMin(from: Int, to: Int) = {
      var ms = C(from)
      var v = from
      while(v != to) {
        v = E(v)
        ms = min(ms, C(v))
      }
      ms
    }

    val stack = ArrayBuffer[Int]()
    var ans = 0
    rep(N) { i =>
      var v = i
      while (!visited(v)) {
        stack += v
        visited(v) = true
        v = E(v)
      }
      if (!computed(v)) {
        ans += findMin(E(v), v)
      }
      stack foreach (v => computed(v) = true)
      stack.clear()
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}


import java.io._
import java.math._
import java.util.StringTokenizer
import scala.collection.mutable.Map

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner
    val n = sc.nextLine.toInt
    val a = sc.nextLine.split(" ").map(_.toInt)
    val freq = Map[Long, Int]()

    // Calculate the prefix sums
    var sum: Long = 0
    for (x <- a) {
      sum += x
      if (freq contains sum) {
        freq(sum) += 1
      } else {
        freq(sum) = 1
      }
    }

    // Get the most frequently appearing prefix sum
    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}

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

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    var ct = mutable.HashMap[Long, Int]();
    var s = 0L
    for (i <- 0 until n) {
      s += a(i)
      ct(s) = ct.getOrElse(s, 0) + 1
    }
    var ans = n
    for (i <- 0 until n) {
      ans = Math.min(n - ct(s), ans)
      s += a(i)
    }
    println(ans)
  }
}

import java.io._
import java.math._
import java.util._
import scala.collection.JavaConversions._

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner
    val n = sc.nextLine.toInt
    val a = sc.nextLine.split(" ").map(_.toInt)
    val freq = new HashMap[Long, Int]

    var sum: Long = 0
    for (x <- a) {
      sum += x
      if (freq containsKey sum) {
        freq put (sum, freq.get(sum) + 1)
      } else {
        freq put (sum, 1)
      }
    }

    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}

import java.io._
import java.math._
import java.util._
import scala.collection.mutable.Map

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner()
    val n = sc.nextInt
    var freq = Map[Long, Int]()

    // Calculate the prefix sums
    var sum: Long = 0
    for (i <- 0 until n) {
      sum += sc.nextInt
      if (freq contains sum) {
        freq(sum) += 1
      } else {
        freq(sum) = 1
      }
    }

    // Get the most frequently appearing prefix sum
    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toInt)
    var p = n - 1
    while (p > 0 && a(p) == 0) {
      p -= 1
    }
    var ans = p
    for (i <- 0 until n) {
      var s = -a(i)
      while (s != 0) {
        p += 1
        s += a(p % n)
      }
      ans = Math.min(ans, p - 1 - i)
    }
    println(ans)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    if (n == 1) {
      println(0)
      return
    }
    var p = n - 1
    while (p > 0 && a(p) == 0) {
      p -= 1
    }
    var ans = p
    for (i <- 0 until n) {
      var s = -a(i)
      while (s != 0) {
        p += 1
        s += a(p % n)
      }
      ans = Math.min(ans, p - 1 - i)
    }
    println(ans)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    if (n == 1) {
      println(0)
      return
    }
    var p = n - 1
    while (p > 0 && a(p) == 0) {
      p -= 1
    }
    var ans = p
    for (i <- 0 until n) {
      if (a(i) != 0) {
        p = i + n
      }
      ans = Math.min(ans, p - 1 - i)
    }
    println(ans)
  }
}

import java.io._
import java.math._
import java.util._
import scala.collection.mutable.Map

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner()
    val n = sc.nextInt
    val a = new Array[Int](n)
    var freq = Map[Int, Int]()

    // Calculate the prefix sums
    var sum = 0
    for (i <- 0 until n) {
      sum += sc.nextInt
      a(i) = sum
      if (freq contains sum) {
        freq(sum) += 1
      } else {
        freq(sum) = 1
      }
    }

    // Get the most frequently appearing prefix sum
    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}


import scala.io.StdIn._

object C extends App {
  def solve(x: Long, y: Long) = {
    if (y > x) -1.toDouble
    else if (x == y) {
      x.toDouble
    } else {
      val k = (x - y) / (2*y)
      if (k == 0) {
        val c = (x.toDouble + y) / (2 * k + 2)
        if (c < y) -1.toDouble
        else c
      } else {
        val A = (x.toDouble - y) / (2 * k)
//        println(A)
        val B = (x.toDouble + y) / (2 * k + 2)
//        println(B)

        if (A < y && B < y) -1.toDouble
        else if (A < y) B
        else if (B < y) A
        else Math.min(A, B)
      }
    }
  }

  val Array(a, b) = readLine().split(" ").map(_.toLong)
  val answer = solve(a, b)

  println(if (answer > 0) "%.12f".format(answer) else "-1")
}

import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val a = sc.nextInt
  val b = sc.nextInt

  val t1 = (a + b) / 2.0
  val t2 = (a - b) / 2.0

  def a(t: Double) = {
    val dv = (t / b).toInt
    if (dv == 0)
      -1
    else
      t / dv
  }

  val a1 = a(t1)
  val a2 = a(t2)

  if (a1 == -1) {
      println(a2)
  } else if (a2 == -1) {
    println(a1)
  } else {
    println(math.min(a1, a2))
  }
}

import java.text.DecimalFormat

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

object C extends App {
  def solve(x: Int, y: Int) = {
    if (y > x) -1.toDouble
    else if (x == y) {
      x.toDouble
    } else {
      val k = (x - y) / (2*y)
      if (k == 0) {
        val c = (x.toDouble + y) / (2 * k + 2)
        if (c > y) -1.toDouble
        else c
      } else {
        val A = (x.toDouble - y) / (2 * k)
//        println(A)
        val B = (x.toDouble + y) / (2 * k + 2)
//        println(B)

        if (A < y && B < y) -1.toDouble
        else if (A < y) B
        else if (B < y) A
        else Math.min(A, B)
      }
    }
  }

  val answer = solve(1, 3)

  println(if (answer > 0) "%.12f".format(answer) else "-1")
}

import scala.io.StdIn._

object C extends App {
  def solve(x: Long, y: Long) = {
    if (y > x) -1.toDouble
    else if (x == y) {
      x.toDouble
    } else {
      val k = (x - y) / (2*y)
      if (k == 0) {
        val c = (x.toDouble + y) / (2 * k + 2)
        if (c > y) -1.toDouble
        else c
      } else {
        val A = (x.toDouble - y) / (2 * k)
//        println(A)
        val B = (x.toDouble + y) / (2 * k + 2)
//        println(B)

        if (A < y && B < y) -1.toDouble
        else if (A < y) B
        else if (B < y) A
        else Math.min(A, B)
      }
    }
  }

  val Array(a, b) = readLine().split(" ").map(_.toLong)
  val answer = solve(a, b)

  println(if (answer > 0) "%.12f".format(answer) else "-1")
}


object A extends App {
  import scala.io.StdIn._
  import scala.annotation.tailrec

  val t = readInt()

  def mult(a: List[List[Int]], b: List[List[Int]]): List[List[Int]] =
    for {
      row <- a
    } yield for {
      col <- b.transpose
    } yield row.zip(col).foldLeft(0) { case (sum, (r, c)) => sum + r * c }

  def binpow(a: List[List[Int]], n: Int): List[List[Int]] =
    (0 to (math.log(n) / math.log(2)).toInt)
      .foldLeft((List(List(1, 0), List(0, 1)), a)) {
        case ((r, a), i) =>
          (if ((1 & (n >> i)) == 1) mult(a, r) else r, mult(a, a))
      }
      ._1

  def fib(n: Int): (Int, Int) = {
    val List(fibn, fibn1) = mult(List(List(0, 1)), binpow(List(List(0, 1), List(1, 1)), n)).head
    (fibn, fibn1)
  }

  (0 until t).foreach { _ =>
    val Array(a, b, n) = readLine().split(" ").map(_.toInt)

    val ans = (0 to n).collectFirst { case i if { val (c1, c2) = fib(i); c2 * a.max(b) + c1 * a.min(b) > n } => i }.get

    println(ans)
  }
}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val abn = readIntLine()
      println(handle(Math.min(abn.head, abn(1)), Math.max(abn.head, abn(1)), abn.last, 0))
    }
  }

  def handle(a: Int, b: Int, n: Int, acc: Int): Int = if (b > n) acc else handle(b, a + b, n, acc + 1)

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}

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

    for (_ <- 1 to nextInt) {
      var a, b, n = nextLong
      var i = 0
      while (a <= n && b <= n) {
        if (a < b) {
          a += b
        } else {
          b += a
        }
        i += 1
      }

      out.println(i)

      out.flush()
    }
  }

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

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, n) = readLine().split(" ").map(_.toInt)

    lazy val fibs: Stream[(Int, Int)] = (0, 0) #:: (1, 1) #:: (fibs zip fibs.tail).map {
      case ((a, _), (b, i)) => (a + b, i + 1)
    }

    val ans = fibs.zip(fibs.tail).collectFirst { case ((f0, i), (f1, _)) if f1 * a.max(b) + f0 * a.min(b) > n => i }.get

    println(ans)
  }
}


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

object sample 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 myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val s1 = readString()
        val s2 = readString()
        var reach = true
        for (i <- 0 until n) {
            if (s1(i) == '1' && s2(i) == '1')
                reach = false
        }
        if (reach)
            writer.println("YES")
        else
            writer.println("NO")
    }
    writer.flush()
}

import scala.io.StdIn.readLine
import scala.util.control.Breaks._

object ComputerGame extends App {
  def solve():Unit = {
    val t = readLine().trim.toInt
    for(_ <- 1 to t) {
      val n = readLine().trim.toInt
      val grid: Array[String] = new Array[String](2)
      grid(0) = readLine().trim
      grid(1) = readLine().trim
      var isPossible:Boolean = true
      breakable {
        for (i <- 0 until n) {
          isPossible = grid(0)(i) == '0' || grid(1)(i) == '0'
          if (!isPossible) break
        }
      }
      val ans = if(isPossible) "YES" else "NO"
      println(ans)
    }
  }
  solve()
}


object Anastasia extends App {

  val Array(n: Int, k: Int) = readLine.split(' ').map(_.toInt)
  val ww: Array[Int] = readLine.split(' ').map(_.toInt)

  val pocketCount = for (w <- ww) yield {
    val ratio = w / k
    val remainder = w % k
    if (remainder == 0) ratio else ratio + 1
  }

  val ratio = pocketCount.sum / 2
  val remainder = pocketCount.sum % 2
  val result = if (remainder == 0) ratio else ratio + 1

  println(result)
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n = read[Int]
    val k = read[Long]
    val pebbles = read[Seq, Long](n)
    val chunks = pebbles.sumWith(i => (i + k - 1)/k)
    val ans = (chunks + 1)/2
    write(ans)
  }

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

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

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

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

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

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

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

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

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

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

/**
  * Created by ruslan on 3/29/17.
  */
object ProblemA extends App {
    import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

class  FastScanner(val in: BufferedReader) {
  var st: StringTokenizer = _;

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

  def nextInt(): Integer = {
    Integer.parseInt(nextToken());
  }

  def nextLong(): Long = {
    nextToken().toLong;
  }

  def nextDouble(): Double = {
    nextToken().toDouble;
  }
}

  val n = in.nextInt();
  val k = in.nextInt();
  var res = 0;

  for (i <- 1 to n) {
    val w = in.nextInt();
    res += w / k;
    if (w % k > 0) res += 1;
  }

  res = res / 2 + (if (res % 2 == 1) 1 else 0)

  println(res)

}


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[Int]]): 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 ?(item: Boolean, first: Any, second: Any): Any = if (item) first else second

  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, in: Main.InputReader) {

  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val n = in.nextInt()
    val k = in.nextInt()
    val a = new Array[Int](k + 1)
    for (_ <- 0 until n) {
      a(in.nextInt()) += 1
    }
    a.sorted
    var count = 0
    var d = (n + 1) / 2
    for {
      i <- k to 0 by -1
      if a(i) > 0
    } yield {
      count += a(i) - (a(i) % 2)
      d -= a(i) / 2
      a(i) = a(i) % 2
    }
    a.sorted
    for {
      i <- a.indices
      if d > 0

    } yield {
      if (a(i) > 0) {
        count += 1
        d -= 1
      }

    }
    out.println(count)

  }
}

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[Int]]): 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, K = ni()
    val C = Array.ofDim[Int](K)
    REP(N) { _ =>
      C(ni() - 1) += 1
    }
    val cntOdd = C.count(_ % 2 == 1)
    val ans = N - cntOdd / 2
    out.println(ans)
  }
}