Skip to content

Instantly share code, notes, and snippets.

@JunJaBoy
Created April 27, 2024 13:18
Show Gist options
  • Save JunJaBoy/2d256e0d177ffe64afc485eb3e65a4e9 to your computer and use it in GitHub Desktop.
Save JunJaBoy/2d256e0d177ffe64afc485eb3e65a4e9 to your computer and use it in GitHub Desktop.
HackerRank/Algorithm/JesseAndCookies kotlin
import java.util.*
import kotlin.*
import kotlin.collections.*
private fun cookies(
sweetness: Int,
cookies: Array<Int>,
): Int {
val result = PriorityQueue<Int>().apply { addAll(cookies) }
var countOfIteration = 0
while (result.peek() < sweetness && result.size > 1) {
val sweetenCookie = result.poll() + result.poll() * 2
result.add(sweetenCookie)
countOfIteration++
}
return if (result.peek() < sweetness) {
-1
} else {
countOfIteration
}
}
// if you use this extension, one of the test cases will throw timeout error.
private fun PriorityQueue<Int>.checkIfSweetenNeeded(sweetness: Int): Boolean =
this.peek() < sweetness && this.size > 1
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val (_, sweetness) = scanner.nextLine().trimEnd()
.split(" ")
.map(String::toInt)
val cookies = scanner.nextLine().trimEnd()
.split(" ")
.map(String::toInt)
.toTypedArray()
val result = cookies(sweetness, cookies)
println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment