| | 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.LongestHarmoniousSubsequence; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LongestHarmoniousSubsequenceDictionary : ILongestHarmoniousSubsequence |
| | 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 FindLHS(int[] nums) |
| 3 | 24 | | { |
| 3 | 25 | | var frequencyDictionary = new Dictionary<int, int>(); |
| | 26 | |
|
| 41 | 27 | | foreach (var num in nums) |
| 16 | 28 | | { |
| 16 | 29 | | if (frequencyDictionary.TryAdd(num, 1)) |
| 10 | 30 | | { |
| 10 | 31 | | continue; |
| | 32 | | } |
| | 33 | |
|
| 6 | 34 | | frequencyDictionary[num]++; |
| 6 | 35 | | } |
| | 36 | |
|
| 3 | 37 | | var maxLength = 0; |
| | 38 | |
|
| 29 | 39 | | foreach (var frequency in frequencyDictionary) |
| 10 | 40 | | { |
| 10 | 41 | | if (!frequencyDictionary.ContainsKey(frequency.Key + 1)) |
| 5 | 42 | | { |
| 5 | 43 | | continue; |
| | 44 | | } |
| | 45 | |
|
| 5 | 46 | | var length = frequency.Value + frequencyDictionary[frequency.Key + 1]; |
| | 47 | |
|
| 5 | 48 | | if (length > maxLength) |
| 3 | 49 | | { |
| 3 | 50 | | maxLength = length; |
| 3 | 51 | | } |
| 5 | 52 | | } |
| | 53 | |
|
| 3 | 54 | | return maxLength; |
| 3 | 55 | | } |
| | 56 | | } |