Advertisement
Teodor92

04. MaxSeq

Jan 6th, 2013
947
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  1. /* Write a program that finds the maximal
  2.  * sequence of equal elements in an array.
  3.         Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1}  {2, 2, 2}.
  4.  */
  5.  
  6. using System;
  7.  
  8. class MaxSequenceInArray
  9. {
  10.     static void Main()
  11.     {
  12.         int[] myArray = { 2, 1, 1, 2, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
  13.         int len = 1;
  14.         int bestLen = 0;
  15.         int bestLenElement = 0;
  16.         for (int i = 0; i < myArray.Length-1; i++)
  17.         {
  18.             if (myArray[i] == myArray[i+1])
  19.             {
  20.                 len++;
  21.             }
  22.             else
  23.             {
  24.                 if (len > bestLen)
  25.                 {
  26.                     bestLen = len;
  27.                     bestLenElement = myArray[i];
  28.                 }
  29.                 len = 1;
  30.             }
  31.         }
  32.         // Special case
  33.         if (len > bestLen)
  34.         {
  35.             bestLen = len;
  36.             bestLenElement = myArray[myArray.Length - 1];
  37.         }
  38.         Console.WriteLine("The longest sequence if form {0} elements of type \"{1}\" .", bestLen, bestLenElement);
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement