Advertisement
elena1234

Longest Consecutive Subsequence

Dec 4th, 2021
1,187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace TopTwoNumber
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             int[] array = new int[] { 2, 6, 1, 9, 4, 5, 3, 3 };
  12.             var sortedArray = array.OrderBy(x => x).ToArray(); // 1 2 3 3 4 5 6 9
  13.             List<int> listWhithUnique = new List<int>();  // 1 2 3 4 5 6 9
  14.          
  15.             // Insert repeated elements only once
  16.             for (int i = 1; i < sortedArray.Length; i++)
  17.             {
  18.                 if (sortedArray[i] != sortedArray[i - 1])
  19.                     listWhithUnique.Add(sortedArray[i-1]);
  20.             }
  21.  
  22.             if(sortedArray[sortedArray.Length-1] != sortedArray[sortedArray.Length-2])
  23.             {
  24.                 listWhithUnique.Add(sortedArray[sortedArray.Length - 1]);
  25.             }
  26.  
  27.             // Find the maximum length by traversing the array
  28.             int count = 0;
  29.             int result = 0;
  30.             for (int i = 0; i < listWhithUnique.Count; i++)
  31.             {
  32.                 if (i > 0 && listWhithUnique[i] == listWhithUnique[i - 1] + 1)
  33.                 {
  34.                     count++;
  35.                 }
  36.                 else
  37.                 {
  38.                     count = 1;
  39.                 }
  40.                 result = Math.Max(result, count);
  41.             }
  42.  
  43.             Console.WriteLine(result);
  44.  
  45.         }
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement