Created
December 30, 2020 12:17
-
-
Save amuradyan/1297729d463a437bb24c62b0e76778d0 to your computer and use it in GitHub Desktop.
Hackerrank `Migratory Birds` problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.hackerrank.com/challenges/migratory-birds/problem | |
// | |
// Input Output | |
// +-----------------------+----------+ | |
// | 6 | 4 | | |
// | 1 4 4 4 5 3 | | | |
// +-----------------------+----------+ | |
// | 11 | 3 | | |
// | 1 2 3 4 5 4 3 2 1 3 4 | | | |
// +-----------------------+----------+ | |
import scala.io._ | |
object MigratoryBirds { | |
def migratoryBirds(arr: Array[Int]): Int = arr.foldLeft(Array(0, 0, 0, 0, 0), 0)((acc, el) => { | |
val sightingsLog = acc._1 | |
val mostCommonBird = acc._2 | |
if(mostCommonBird == 0) { | |
sightingsLog(el - 1) = 1 | |
(sightingsLog, el) | |
} else { | |
val sightingsOfGivenSpecies = sightingsLog(el - 1) + 1 | |
val sightingsOfMostCommonBird = sightingsLog(mostCommonBird - 1) | |
sightingsLog(el - 1) = sightingsOfGivenSpecies | |
val newMostCommonBird = | |
if (sightingsOfGivenSpecies > sightingsOfMostCommonBird) el | |
else if(sightingsOfGivenSpecies == sightingsOfMostCommonBird && el < mostCommonBird) el | |
else mostCommonBird | |
(sightingsLog, newMostCommonBird) | |
} | |
})._2 | |
def main(args: Array[String]): Unit = { | |
val arrCount = StdIn.readLine.trim.toInt | |
val arr = StdIn.readLine.replaceAll("\\s+$", "").split(" ").map(_.trim.toInt) | |
val result = migratoryBirds(arr) | |
println(result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment