Minimum Operations to Make a Uni-Value Grid LeetCode solution in Python

1
class Solution:
2
def minOperations(self, grid: List[List[int]], x: int) -> int:
3

4
m = len(grid)
5
n = len(grid[0])
6

7
# handle the edge case
8
if m == 1 and n == 1:
9
return 0
10

11
# transform grid to array, easier to operate
12
arr = []
13
for i in range(m):
14
arr += grid[i]
15

16
arr.sort()
17

18
# the median is arr[len(arr)//2] when len(arr) is odd
19
# or may be arr[len(arr)//2] and arr[len(arr)//2-1] when len(arr) is even.
20
cand1 = arr[len(arr) // 2]
21
cand2 = arr[len(arr) // 2 - 1]
22

23
return min(
24
self.get_num_operations_to_target(grid, cand1, x),
25
self.get_num_operations_to_target(grid, cand2, x),
26
)
27

28
def get_num_operations_to_target(self, grid, target, x):
29
"""Get the total number of operations to transform all grid elements to the target value."""
30
ans = 0
31
for i in range(len(grid)):
32
for j in range(len(grid[0])):
33
if abs(grid[i][j] - target) % x != 0:
34
return -1
35
else:
36
ans += abs(grid[i][j] - target) // x
37

38
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0