Leetcode 2160 Solution

This article provides solution to leetcode question 2160 (minimum-operations-to-make-a-uni-value-grid)

https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid

Solution

class Solution:
    def minOperations(self, grid: List[List[int]], x: int) -> int:
        values = [val for row in grid for val in row]

        values.sort()

        mid_val = values[len(values) // 2]

        ans = 0
        for value in values:
            if abs(mid_val - value) % x != 0:
                return -1

            ans += abs(mid_val - value) // x
        return ans