| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.MinimumDominoRotationsForEqualRow; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class MinimumDominoRotationsForEqualRowGreedy : IMinimumDominoRotationsForEqualRow |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n) |
| | | 19 | | /// Space complexity - O(1) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="tops"></param> |
| | | 22 | | /// <param name="bottoms"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public int MinDominoRotations(int[] tops, int[] bottoms) |
| | 3 | 25 | | { |
| | 3 | 26 | | var result = TryTarget(tops, bottoms, tops[0]); |
| | | 27 | | |
| | 3 | 28 | | if (result != -1 || tops[0] == bottoms[0]) |
| | 2 | 29 | | { |
| | 2 | 30 | | return result; |
| | | 31 | | } |
| | | 32 | | |
| | 1 | 33 | | return TryTarget(tops, bottoms, bottoms[0]); |
| | 3 | 34 | | } |
| | | 35 | | |
| | | 36 | | private static int TryTarget(int[] tops, int[] bottoms, int target) |
| | 4 | 37 | | { |
| | 4 | 38 | | var topRotations = 0; |
| | 4 | 39 | | var bottomRotations = 0; |
| | | 40 | | |
| | 48 | 41 | | for (var i = 0; i < tops.Length; i++) |
| | 22 | 42 | | { |
| | 22 | 43 | | if (tops[i] != target && bottoms[i] != target) |
| | 2 | 44 | | { |
| | 2 | 45 | | return -1; |
| | | 46 | | } |
| | | 47 | | |
| | 20 | 48 | | if (tops[i] != target) |
| | 7 | 49 | | { |
| | 7 | 50 | | topRotations++; |
| | 7 | 51 | | } |
| | | 52 | | |
| | 20 | 53 | | if (bottoms[i] != target) |
| | 8 | 54 | | { |
| | 8 | 55 | | bottomRotations++; |
| | 8 | 56 | | } |
| | 20 | 57 | | } |
| | | 58 | | |
| | 2 | 59 | | return Math.Min(topRotations, bottomRotations); |
| | 4 | 60 | | } |
| | | 61 | | } |