Advertisement
Guest User

Untitled

a guest
Jan 28th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.80 KB | None | 0 0
  1. import java.util.*
  2.  
  3. data class Context(val sum: Int, val coins: List<Int>)
  4.  
  5. fun coins(amount: Int, coins: List<Int>): List<Int> {
  6.     val sorted = coins.distinct().sortedDescending()
  7.     val initialContext = Context(0, listOf())
  8.     val queue = ArrayDeque<Context>()
  9.     queue.offer(initialContext)
  10.     while (queue.isNotEmpty()) {
  11.         val context = queue.poll()
  12.         if (context.sum == amount) {
  13.             return context.coins
  14.         }
  15.         sorted.asSequence()
  16.             .filter { context.coins.isEmpty() || it <= context.coins.last() }
  17.             .filter { context.sum + it <= amount }
  18.             .forEach { queue.offer(Context(context.sum + it, context.coins + it)) }
  19.     }
  20.     return listOf()
  21. }
  22.  
  23. fun main() {
  24.     val coins = coins(76, listOf(1, 3, 4, 10))
  25.     println(coins)
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement