How to find the maximum value we can achieve by picking k elements from a list in Kotlin

1 Answer

0 votes
fun maxSumOfK(lst: List<Int>, k: Int): Int {
    return lst.sortedDescending()
              .take(k)
              .sum()
}
 
fun main() {
    val lst = listOf(11, 2, 4, 9, 3, 6, 5, 1)
    val k = 3
 
    println(maxSumOfK(lst, k)) 
}
 
 
 
/*
run:
 
26
 
*/

 



answered Apr 6 by avibootz
edited Apr 6 by avibootz

Related questions

...