| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MinimumOperationsToMakeUniValueGrid; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MinimumOperationsToMakeUniValueGridSorting : IMinimumOperationsToMakeUniValueGrid |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(log n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="grid"></param> |
| | 22 | | /// <param name="x"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int MinOperations(int[][] grid, int x) |
| 3 | 25 | | { |
| 3 | 26 | | var rows = grid.Length; |
| 3 | 27 | | var cols = grid[0].Length; |
| 3 | 28 | | var remainder = grid[0][0] % x; |
| | 29 | |
|
| 3 | 30 | | var items = new List<int>(rows * cols); |
| | 31 | |
|
| 18 | 32 | | foreach (var row in grid) |
| 5 | 33 | | { |
| 34 | 34 | | foreach (var cell in row) |
| 10 | 35 | | { |
| 10 | 36 | | if (cell % x != remainder) |
| 1 | 37 | | { |
| 1 | 38 | | return -1; |
| | 39 | | } |
| | 40 | |
|
| 9 | 41 | | items.Add(cell); |
| 9 | 42 | | } |
| 4 | 43 | | } |
| | 44 | |
|
| 2 | 45 | | items.Sort(); |
| | 46 | |
|
| 2 | 47 | | var median = items[items.Count / 2]; |
| | 48 | |
|
| 10 | 49 | | return items.Sum(item => Math.Abs(item - median) / x); |
| 3 | 50 | | } |
| | 51 | | } |