LeetCode/kt/put-marbles-in-bags.kt
2025-03-31 08:40:12 +02:00

18 lines
477 B
Kotlin

class Solution {
fun putMarbles(
weights: IntArray,
k: Int,
): Long =
weights
.zip(weights.drop(1))
.map { (w1, w2) -> (w1 + w2).toLong() }
.sorted()
.let { pairs ->
(0..k - 2)
.map { i ->
weights.size - 2 - i to i
}.sumOf { (i, j) ->
pairs[i] - pairs[j]
}
}
}