Advertisement
Statev

LongestIncreasingSubArray

Dec 21st, 2011
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace _18.LongestIncreasingSubArray
  6. {
  7.     class LongestIncreasingSubArray
  8.     {
  9.         static int[] longestIncreasingSubsequence(int[] array)
  10.         {
  11.             int[] increasingLengths = new int[array.Length];
  12.             increasingLengths[0] = 1;
  13.             for (int i = 1; i < increasingLengths.Length; i++)
  14.             {
  15.                 int maxLength = 0;
  16.                 for (int j = 0; j < i; j++)
  17.                 {
  18.                     if (array[j] <= array[i] && increasingLengths[j] > maxLength)
  19.                     {
  20.                         maxLength = increasingLengths[j];
  21.                     }
  22.                 }
  23.                 increasingLengths[i] = maxLength + 1;
  24.             }
  25.  
  26.             int[] returnedSubArray = new int[increasingLengths.Max()];
  27.             int serialNumber = increasingLengths.Max();
  28.  
  29.             for (int i = array.Length - 1; i >= 0; i--)
  30.             {
  31.                 if (serialNumber == increasingLengths[i])
  32.                 {
  33.                     returnedSubArray[serialNumber - 1] = array[i];
  34.                     serialNumber--;
  35.                 }
  36.             }
  37.  
  38.             return returnedSubArray;
  39.         }
  40.  
  41.         static void Main(string[] args)
  42.         {
  43.             int[] array = { 6, 1, 4, 3, 0, 3, 6, 4, 5 };
  44.             int[] longestIncreasingSub = longestIncreasingSubsequence(array);
  45.             Array.ForEach(longestIncreasingSub, Console.WriteLine);
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement