Andrexxelles

Method2

Jan 7th, 2025
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. public int FindLHS2(int[] nums)
  2. {
  3. int length = 0;
  4.  
  5. // Getting all numbers in the array without diplicates
  6. HashSet<int> uniqueNumbers = new HashSet<int>(nums);
  7.  
  8. // Stores the count of a number
  9. Dictionary<int, int> countNumber = new Dictionary<int, int>();
  10.  
  11. // Counting the number of repetitions
  12. foreach (var number in uniqueNumbers)
  13. {
  14. countNumber[number] = nums.Count(_num => _num == number);
  15. }
  16.  
  17. // Finding the longest combination
  18. int _length;
  19. foreach (KeyValuePair<int, int> repeats in countNumber)
  20. {
  21. _length = repeats.Value;
  22.  
  23. _length += countNumber.GetValueOrDefault(repeats.Key + 1, 0);
  24.  
  25. length = Math.Max(length, _length);
  26. }
  27.  
  28.  
  29. return length;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment