Advertisement
ntodorova

Arrays - 04_MaximalSequence

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