简体   繁体   中英

How do I check if sum of any N numbers of items in a list equals or greater than a value in Kotlin

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:

  1. Sort the list in descending order
  2. Check if the sum of the first N items is >= target. If that is not true then any other combination won't be >= target for sure.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM