Reputation: 2641
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?
Upvotes: 0
Views: 374
Reputation: 10713
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))
, i.e. the slowest operation is sorting. Also, this approach would work even if numbers
contains less than n
elements
Upvotes: 2
Reputation: 2243
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!
Upvotes: 1