| | 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.MinimumSwapsToGroupAll1Together2; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MinimumSwapsToGroupAll1Together2SlidingWindow : IMinimumSwapsToGroupAll1Together2 |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int MinSwaps(int[] nums) |
| 3 | 24 | | { |
| 24 | 25 | | var totalOnes = nums.Count(num => num == 1); |
| | 26 | |
|
| 3 | 27 | | if (totalOnes == 0) |
| 0 | 28 | | { |
| 0 | 29 | | return 0; |
| | 30 | | } |
| | 31 | |
|
| 3 | 32 | | var windowedArray = nums.Concat(nums.Take(totalOnes)).ToArray(); |
| | 33 | |
|
| 3 | 34 | | var currentZeroCount = 0; |
| | 35 | |
|
| 28 | 36 | | for (var i = 0; i < totalOnes; i++) |
| 11 | 37 | | { |
| 11 | 38 | | if (windowedArray[i] == 0) |
| 5 | 39 | | { |
| 5 | 40 | | currentZeroCount++; |
| 5 | 41 | | } |
| 11 | 42 | | } |
| | 43 | |
|
| 3 | 44 | | var minSwaps = currentZeroCount; |
| | 45 | |
|
| 42 | 46 | | for (var i = 1; i < nums.Length; i++) |
| 18 | 47 | | { |
| 18 | 48 | | if (windowedArray[i - 1] == 0) |
| 8 | 49 | | { |
| 8 | 50 | | currentZeroCount--; |
| 8 | 51 | | } |
| | 52 | |
|
| 18 | 53 | | if (windowedArray[i + totalOnes - 1] == 0) |
| 7 | 54 | | { |
| 7 | 55 | | currentZeroCount++; |
| 7 | 56 | | } |
| | 57 | |
|
| 18 | 58 | | minSwaps = Math.Min(minSwaps, currentZeroCount); |
| 18 | 59 | | } |
| | 60 | |
|
| 3 | 61 | | return minSwaps; |
| 3 | 62 | | } |
| | 63 | | } |