aboutsummaryrefslogtreecommitdiff
path: root/min_ops_uni_val_grid.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-25 21:42:26 -0600
committerJack Sangdahl <[email protected]>2025-03-25 21:42:26 -0600
commitd95541ed50562a0b6b8deeff1a9eacaef7e4c6dc (patch)
treeda8b85ac9fe8af639d1131145e38aa4aec5e7689 /min_ops_uni_val_grid.py
parentbf408cd8346c296ee1960a6a1a03fe1270296e49 (diff)
downloadleetcode-d95541ed50562a0b6b8deeff1a9eacaef7e4c6dc.tar.gz
leetcode-d95541ed50562a0b6b8deeff1a9eacaef7e4c6dc.zip
2033. minimum operations to make a uni-value grid
Diffstat (limited to 'min_ops_uni_val_grid.py')
-rw-r--r--min_ops_uni_val_grid.py32
1 files changed, 32 insertions, 0 deletions
diff --git a/min_ops_uni_val_grid.py b/min_ops_uni_val_grid.py
new file mode 100644
index 0000000..b417eb2
--- /dev/null
+++ b/min_ops_uni_val_grid.py
@@ -0,0 +1,32 @@
+# 2033. Minimum Operations to Make a Uni-Value Grid
+
+"""
+you are given a 2d integer 'grid' of size 'm x n' and an integer 'x'. in one
+operation, you can add 'x' to or subtract 'x' from any element in the 'grid'.
+a uni-value grid is a grid where all the elements of it are equal. return the
+minimum number of operations to make the grid uni-valued. if it is not
+possible, return -1.
+"""
+
+
+class Solution(object):
+ def minOperations(self, grid, x):
+ """
+ :type grid: List[List[int]]
+ :type x: int
+ :rtype: int
+ """
+ vals = sorted([i for j in grid for i in j])
+ diff = [abs(i - vals[0]) % x for i in vals]
+ if any(i != 0 for i in diff):
+ return -1
+ med = vals[len(vals) // 2]
+ ans = sum(abs(i - med) // x for i in vals)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minOperations(grid=[[2, 4], [6, 8]], x=2))
+ print(obj.minOperations(grid=[[1, 5], [2, 3]], x=1))
+ print(obj.minOperations(grid=[[1, 2], [3, 4]], x=2))