Advertisement
Klaxon

[C# Arrays] Maximal Sequence

Jul 15th, 2013
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. // 4. Write a program that finds the maximal sequence of equal elements in an array.
  2. //    Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} -> {2, 2, 2}.
  3.  
  4. using System;
  5.  
  6. class MaximalSequence
  7. {
  8.     static void Main()
  9.     {
  10.         // Make an array and get the size
  11.         int length = int.Parse(Console.ReadLine());
  12.         int[] array = new int[length];
  13.  
  14.         // Help variables
  15.         int len = 1;
  16.         int bestLen = 0;
  17.         int bestStart = 0;
  18.  
  19.         // Loop to fill up the array
  20.         for (int i = 0; i < length; i++)
  21.         {
  22.             array[i] = int.Parse(Console.ReadLine());
  23.  
  24.             // Check is the array is filled up
  25.             if (i == length - 1)
  26.             {
  27.                 // Loop for comparing every number with the next
  28.                 for (int j = 0; j < i; j++)
  29.                 {
  30.                     if (array[j] == array[j + 1])
  31.                     {
  32.                         len++;
  33.                     }
  34.                     else
  35.                     {
  36.                         len = 1; // We make that 1 for current number
  37.                     }
  38.  
  39.                     // ..if there is a better length
  40.                     if (len >= bestLen)
  41.                     {
  42.                         bestLen = len;
  43.                         bestStart = array[j];
  44.                     }
  45.                 }
  46.             }
  47.         }
  48.  
  49.         // Printing
  50.         Console.Write("{");
  51.         for (int i = 0; i < bestLen; i++)
  52.         {
  53.             if (i == bestLen - 1)
  54.             {
  55.                 Console.Write(bestStart);
  56.             }
  57.             else
  58.             {
  59.                 Console.Write("{0}, ", bestStart);
  60.             }
  61.         }
  62.         Console.WriteLine("}");
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement