2033. Minimum Operations to Make a Uni-Value Grid
UnknownView on LeetCode
Problem Overview
Minimum Operations to Make a Uni-Value Grid (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Math pattern in coding interviews. Flatten grid; check all values share same remainder mod x; sort and use median as target.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Flatten grid; check all values share same remainder mod x; sort and use median as target.
2033.cs
C#
// Approach: Flatten grid; check all values share same remainder mod x; sort and use median as target.
// Time: O(mn log(mn)) Space: O(mn)
public class Solution
{
public int MinOperations(int[][] grid, int x)
{
int m = grid.Length;
int n = grid[0].Length;
int[] arr = new int[m * n];
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
arr[i * n + j] = grid[i][j];
}
if (arr.Any(a => (a - arr[0]) % x != 0))
return -1;
int ans = 0;
Array.Sort(arr);
foreach (var a in arr)
ans += Math.Abs(a - arr[arr.Length / 2]) / x;
return ans;
}
}Was this solution helpful?
Related Problems
- 179. Largest Number(Medium)
- 781. Rabbits in Forest(Medium)
- 807. Max Increase to Keep City Skyline(Medium)
- 840. Magic Squares In Grid(Medium)
- 857. Minimum Cost to Hire K Workers(Hard)
- 885. Spiral Matrix III(Medium)