|
| 1 | +<p>You are given a 2D integer <code>grid</code> of size <code>m x n</code> and an integer <code>x</code>. In one operation, you can <strong>add</strong> <code>x</code> to or <strong>subtract</strong> <code>x</code> from any element in the <code>grid</code>.</p> |
| 2 | + |
| 3 | +<p>A <strong>uni-value grid</strong> is a grid where all the elements of it are equal.</p> |
| 4 | + |
| 5 | +<p>Return <em>the <strong>minimum</strong> number of operations to make the grid <strong>uni-value</strong></em>. If it is not possible, return <code>-1</code>.</p> |
| 6 | + |
| 7 | +<p> </p> |
| 8 | +<p><strong class="example">Example 1:</strong></p> |
| 9 | +<img alt="" src="https://assets.leetcode.com/uploads/2021/09/21/gridtxt.png" style="width: 164px; height: 165px;" /> |
| 10 | +<pre> |
| 11 | +<strong>Input:</strong> grid = [[2,4],[6,8]], x = 2 |
| 12 | +<strong>Output:</strong> 4 |
| 13 | +<strong>Explanation:</strong> We can make every element equal to 4 by doing the following: |
| 14 | +- Add x to 2 once. |
| 15 | +- Subtract x from 6 once. |
| 16 | +- Subtract x from 8 twice. |
| 17 | +A total of 4 operations were used. |
| 18 | +</pre> |
| 19 | + |
| 20 | +<p><strong class="example">Example 2:</strong></p> |
| 21 | +<img alt="" src="https://assets.leetcode.com/uploads/2021/09/21/gridtxt-1.png" style="width: 164px; height: 165px;" /> |
| 22 | +<pre> |
| 23 | +<strong>Input:</strong> grid = [[1,5],[2,3]], x = 1 |
| 24 | +<strong>Output:</strong> 5 |
| 25 | +<strong>Explanation:</strong> We can make every element equal to 3. |
| 26 | +</pre> |
| 27 | + |
| 28 | +<p><strong class="example">Example 3:</strong></p> |
| 29 | +<img alt="" src="https://assets.leetcode.com/uploads/2021/09/21/gridtxt-2.png" style="width: 164px; height: 165px;" /> |
| 30 | +<pre> |
| 31 | +<strong>Input:</strong> grid = [[1,2],[3,4]], x = 2 |
| 32 | +<strong>Output:</strong> -1 |
| 33 | +<strong>Explanation:</strong> It is impossible to make every element equal. |
| 34 | +</pre> |
| 35 | + |
| 36 | +<p> </p> |
| 37 | +<p><strong>Constraints:</strong></p> |
| 38 | + |
| 39 | +<ul> |
| 40 | + <li><code>m == grid.length</code></li> |
| 41 | + <li><code>n == grid[i].length</code></li> |
| 42 | + <li><code>1 <= m, n <= 10<sup>5</sup></code></li> |
| 43 | + <li><code>1 <= m * n <= 10<sup>5</sup></code></li> |
| 44 | + <li><code>1 <= x, grid[i][j] <= 10<sup>4</sup></code></li> |
| 45 | +</ul> |
0 commit comments