| | 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.FruitIntoBaskets; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FruitIntoBasketsFrequencyDictionary : IFruitIntoBaskets |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="fruits"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int TotalFruit(int[] fruits) |
| 3 | 24 | | { |
| 3 | 25 | | var maximumNumberOfFruits = 0; |
| | 26 | |
|
| 3 | 27 | | var fruitsFrequencyDictionary = new Dictionary<int, int>(); |
| | 28 | |
|
| 3 | 29 | | var left = 0; |
| | 30 | |
|
| 30 | 31 | | for (var right = 0; right < fruits.Length; right++) |
| 12 | 32 | | { |
| 12 | 33 | | fruitsFrequencyDictionary[fruits[right]] = fruitsFrequencyDictionary.GetValueOrDefault(fruits[right]) + 1; |
| | 34 | |
|
| 14 | 35 | | while (fruitsFrequencyDictionary.Count > 2) |
| 2 | 36 | | { |
| 2 | 37 | | if (fruitsFrequencyDictionary[fruits[left]] == 1) |
| 2 | 38 | | { |
| 2 | 39 | | fruitsFrequencyDictionary.Remove(fruits[left]); |
| 2 | 40 | | } |
| | 41 | | else |
| 0 | 42 | | { |
| 0 | 43 | | fruitsFrequencyDictionary[fruits[left]]--; |
| 0 | 44 | | } |
| | 45 | |
|
| 2 | 46 | | left++; |
| 2 | 47 | | } |
| | 48 | |
|
| 12 | 49 | | maximumNumberOfFruits = Math.Max(maximumNumberOfFruits, right - left + 1); |
| 12 | 50 | | } |
| | 51 | |
|
| 3 | 52 | | return maximumNumberOfFruits; |
| 3 | 53 | | } |
| | 54 | | } |