kt: add «2551. Put Marbles in Bags»

URL:	https://leetcode.com/problems/put-marbles-in-bags/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-31 08:40:12 +02:00
parent 76d3e0eab1
commit efff2000aa
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

18
kt/put-marbles-in-bags.kt Normal file
View file

@ -0,0 +1,18 @@
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]
}
}
}