TheBulgarianWolf

Longest Increasing Subsequence

Oct 26th, 2020
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.00 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Linq;
  5. using System.Numerics;
  6. using System.Threading;
  7.  
  8. namespace SoftuniExercisesWithVariables
  9. {
  10.     using System;
  11.     using System.Collections.Generic;
  12.     using System.Linq;
  13.     public class LongestIncreasingSubsequence
  14.     {
  15.         public static void Main()
  16.         {
  17.             var sequence = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToArray();
  18.             var longestSeq = FindLongestIncreasingSubsequence(sequence);
  19.             Console.WriteLine("Longest increasing subsequence (LIS)");
  20.             //   Console.WriteLine("  Length: {0}", longestSeq.Length);
  21.             Console.WriteLine("  Sequence: [{0}]", string.Join(", ", longestSeq));
  22.         }
  23.  
  24.         public static int[] FindLongestIncreasingSubsequence(int[] sequence)
  25.         {
  26.             int[] length = new int[sequence.Length];
  27.             int[] prev = new int[sequence.Length];
  28.             int maxLength = 0;
  29.             int lastIndex = -1;
  30.  
  31.             for (int i = 0; i < sequence.Length; i++)
  32.             {
  33.                 length[i] = 1;
  34.                 prev[i] = -1;
  35.  
  36.                 for (int j = 0; j < i; j++)
  37.                 {
  38.                     if (sequence[j] < sequence[i] && length[j] >= length[i])
  39.                     {
  40.                         length[i] = 1 + length[j];
  41.                         prev[i] = j;
  42.                     }
  43.                 }
  44.  
  45.                 if (length[i] > maxLength)
  46.                 {
  47.                     maxLength = length[i];
  48.                     lastIndex = i;
  49.                 }
  50.             }
  51.  
  52.             var longestSeq = new List<int>();
  53.             for (int i = 0; i < maxLength; i++)
  54.             {
  55.                 longestSeq.Add(sequence[lastIndex]);
  56.                 lastIndex = prev[lastIndex];
  57.             }
  58.  
  59.             longestSeq.Reverse();
  60.             return longestSeq.ToArray();
  61.         }
  62.     }
  63. }
Add Comment
Please, Sign In to add comment