Advertisement
ntodorova

Arrays - 05_MaximalIncreasingSequence

Jan 13th, 2013
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. using System;
  2.  
  3. /*
  4.  * 5. Write a program that finds the maximal increasing sequence in an array.
  5.  * Example: {3, 2, 3, 4, 2, 2, 4} -> {2, 3, 4}
  6.  */
  7. class MaximalIncreasingSequence
  8. {
  9.     static void Main()
  10.     {
  11.         int[] arr = { 3, 2, 3, 4, 5, 2, 4 };
  12.  
  13.         int start = arr[0];
  14.         int endIndex = arr[0];
  15.  
  16.         int startInt = arr[0];
  17.         int length = 1;
  18.         int bestLength = length;
  19.  
  20.         for (int i = 0; i < arr.Length; i++)
  21.         {
  22.             if (i != arr.Length - 1)
  23.             {
  24.  
  25.                 if (arr[i] < arr[i + 1])
  26.                 {
  27.                     length++;
  28.  
  29.                     if (length > bestLength)
  30.                     {
  31.                         bestLength = length;
  32.                         endIndex = i + 1;
  33.                     }
  34.                 }
  35.                 else
  36.                 {
  37.                     length = 0;
  38.                 }
  39.             }
  40.             else if (arr[i - 1] < arr[i])
  41.             {
  42.                 bestLength++;
  43.             }
  44.         }
  45.  
  46.         Console.WriteLine("{ 3, 2, 3, 4, 5, 2, 4 }");
  47.         Console.WriteLine("The maximal increasing sequence of elements is: ");
  48.  
  49.         Console.Write("{ ");
  50.  
  51.         for (int i = endIndex + 1 - bestLength; i <= endIndex; i++)
  52.         {
  53.  
  54.             if (i == endIndex)
  55.             {
  56.                 Console.Write("{0}", arr[i]);
  57.             }
  58.             else
  59.             {
  60.                 Console.Write("{0}, ", arr[i]);
  61.             }
  62.         }
  63.  
  64.         Console.WriteLine(" }");
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement