| | 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.ContiguousArray; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ContiguousArrayDictionary : IContiguousArray |
| | 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 FindMaxLength(int[] nums) |
| 8 | 24 | | { |
| 8 | 25 | | var maxLength = 0; |
| 8 | 26 | | var count = 0; |
| 8 | 27 | | var dictionary = new Dictionary<int, int> { { 0, -1 } }; |
| | 28 | |
|
| 156 | 29 | | for (var i = 0; i < nums.Length; i++) |
| 70 | 30 | | { |
| 70 | 31 | | count += nums[i] == 1 ? 1 : -1; |
| | 32 | |
|
| 70 | 33 | | if (!dictionary.TryAdd(count, i)) |
| 46 | 34 | | { |
| 46 | 35 | | maxLength = Math.Max(maxLength, i - dictionary[count]); |
| 46 | 36 | | } |
| 70 | 37 | | } |
| | 38 | |
|
| 8 | 39 | | return maxLength; |
| 8 | 40 | | } |
| | 41 | | } |