Advertisement
dimipan80

Longest Increasing Subsequence (using Dynamic Programing)

Mar 26th, 2017
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | None | 0 0
  1. /*
  2. Longest Increasing Subsequence (LIS)
  3. Read a list of integers and find the longest increasing subsequence (LIS).
  4. If several such exist, print the leftmost.
  5. • Assume we have n numbers in an array nums[0…n-1].
  6. • Let len[p] holds the length of the longest increasing subsequence (LIS) ending at position p.
  7. • In a for loop, we calculate shall len[p] for p = 0 … n-1 as follows:
  8.     o   Let left is the leftmost position on the left of p (left < p), such that len[left] is the maximal possible.
  9.     o   Then, len[p] = 1 + len[left]. If left does not exist, len[p] = 1.
  10.     o   Also save prev[p] = left (we hold if prev[] the previous position, used to obtain the best length for position p).
  11. • Once the values for len[0…n-1] are calculated, restore the LIS starting from position p such that len[p] is maximal
  12.     and go back and back through p = prev[p].
  13. */
  14.  
  15.     using System;
  16.     using System.Collections.Generic;
  17.     using System.Linq;
  18.  
  19.     internal static class LongestIncreasingSubsequence
  20.     {
  21.         private static void Main()
  22.         {
  23.             var numbers = Console.ReadLine().Split()
  24.                 .Select(int.Parse)
  25.                 .ToArray();
  26.  
  27.             var maxLen = 0;
  28.             var lastIndex = -1;
  29.             var len = new int[numbers.Length];
  30.             var prev = new int[numbers.Length];
  31.             for (int i = 0; i < numbers.Length; i++)
  32.             {
  33.                 len[i] = 1;
  34.                 prev[i] = -1;
  35.                 for (int j = 0; j < i; j++)
  36.                 {
  37.                     if (numbers[j] < numbers[i] && len[j] + 1 > len[i])
  38.                     {
  39.                         len[i] = len[j] + 1;
  40.                         prev[i] = j;
  41.                     }
  42.                 }
  43.  
  44.                 if (len[i] > maxLen)
  45.                 {
  46.                     maxLen = len[i];
  47.                     lastIndex = i;
  48.                 }
  49.             }
  50.  
  51.             var longestSeq = new Stack<int>();
  52.             while (lastIndex > -1)
  53.             {
  54.                 longestSeq.Push(numbers[lastIndex]);
  55.                 lastIndex = prev[lastIndex];
  56.             }
  57.  
  58.             Console.WriteLine(string.Join(" ", longestSeq));
  59.         }
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement