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:
parent
8fa1d853ff
commit
3a02219766
1 changed files with 31 additions and 0 deletions
31
kt/minimum-operations-to-make-a-uni-value-grid.kt
Normal file
31
kt/minimum-operations-to-make-a-uni-value-grid.kt
Normal 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
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue