kt: add «2033. Minimum Operations to Make a Uni-Value Grid»

URL:	https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-26 08:29:21 +01:00
parent 8fa1d853ff
commit 3a02219766
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,31 @@
class Solution {
fun minOperations(
grid: Array<IntArray>,
x: Int,
): Int {
if (grid.any { row -> row.any { it -> it % x != grid[0][0] % x } }) {
// can't make them equal by a multiple of x
return -1
}
val nums = grid.flatMap { it.asIterable() }.sorted()
var ops = 0
var (l, r) = 0 to nums.size - 1
while (l < r) {
when {
l < nums.size - r - 1 -> {
ops += (l + 1) * (nums[l + 1] - nums[l]) / x
l++
}
else -> {
ops += (nums.size - r) * (nums[r] - nums[r - 1]) / x
r--
}
}
}
return ops
}
}