Is it possible to check if any combination of n numbers of Items in a list is greater than or equal to a number? and how?
What I would do is:
An example is:
val numbers = listOf(5, 2, 8, 12, 4, 9, 0)
val target = 29
val n = 3
val result = numbers.sortedDescending().take(n).sum() >= target
println(result) // true if target is <= 29, false otherwise
Note that this approach takes O(n * log(n))
, ie the slowest operation is sorting. Also, this approach would work even if numbers
contains less than n
elements
You should probably try this:
private fun hasLargerSum(compareTo: Int, n: Int, list: List<Int>): Boolean =
list.sorted()
.takeLast(n)
.sum() >= compareTo
in this case it will take N elements of the list sorted ascending, sum it and compare to the number you need.
Cheers!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.