URL: https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/ Signed-off-by: Matej Focko <me@mfocko.xyz>
31 lines
782 B
Kotlin
31 lines
782 B
Kotlin
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
|
||
}
|
||
}
|