Anga
Anga

Reputation: 2641

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?

Upvotes: 0

Views: 374

Answers (2)

user2340612
user2340612

Reputation: 10713

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)), i.e. the slowest operation is sorting. Also, this approach would work even if numbers contains less than n elements

Upvotes: 2

r2rek
r2rek

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

Related Questions