2033. Minimum Operations to Make a Uni-Value Grid Medium

@problem@discussion
#Array#Math#Sorting#Matrix



1/**
2 * [2033] Minimum Operations to Make a Uni-Value Grid
3 *
4 * 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.
5 * A uni-value grid is a grid where all the elements of it are equal.
6 * Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.
7 *  
8 * Example 1:
9 * <img alt="" src="https://assets.leetcode.com/uploads/2021/09/21/gridtxt.png" style="width: 164px; height: 165px;" />
10 * Input: grid = [[2,4],[6,8]], x = 2
11 * Output: 4
12 * Explanation: We can make every element equal to 4 by doing the following: 
13 * - Add x to 2 once.
14 * - Subtract x from 6 once.
15 * - Subtract x from 8 twice.
16 * A total of 4 operations were used.
17 * 
18 * Example 2:
19 * <img alt="" src="https://assets.leetcode.com/uploads/2021/09/21/gridtxt-1.png" style="width: 164px; height: 165px;" />
20 * Input: grid = [[1,5],[2,3]], x = 1
21 * Output: 5
22 * Explanation: We can make every element equal to 3.
23 * 
24 * Example 3:
25 * <img alt="" src="https://assets.leetcode.com/uploads/2021/09/21/gridtxt-2.png" style="width: 164px; height: 165px;" />
26 * Input: grid = [[1,2],[3,4]], x = 2
27 * Output: -1
28 * Explanation: It is impossible to make every element equal.
29 * 
30 *  
31 * Constraints:
32 * 
33 * 	m == grid.length
34 * 	n == grid[i].length
35 * 	1 <= m, n <= 10^5
36 * 	1 <= m * n <= 10^5
37 * 	1 <= x, grid[i][j] <= 10^4
38 * 
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/
43// discuss: https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47impl Solution {
48    pub fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32 {
49        0
50    }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_2033() {
61    }
62}
63


Back
© 2025 bowen.ge All Rights Reserved.