fork(4) download
using System;
using System.Collections.Generic;
using System.Linq;

namespace Interview_ConsecutiveSequence
{
    class Program
    {
        public static int GetMaxLengthConsecutiveSequence(int[] numbers)
        {
            HashSet<int> set = BuildHashSet(numbers);
            return AnalyzeHashSet(set);
        }

        private static HashSet<int> BuildHashSet(int[] numbers)
        {
            var set = new HashSet<int>();
            foreach(int number in numbers)
            {
                set.Add(number);
            }

            return set;
        }

        private static int AnalyzeHashSet(HashSet<int> set)
        {
            int maxCount = 0;
            while(set.Count > 0)
            {
                int number = set.First();
                int count = 0;
                int toDelete = number;

                while(set.Remove(toDelete))
                {
                    count++;
                    toDelete++;
                }

                toDelete = number - 1;
                while(set.Remove(toDelete))
                {
                    count++;
                    toDelete--;
                }

                if(count > maxCount)
                {
                    maxCount = count;
                }
            }

            return maxCount;
        }

        private static void Test(string testName, int[] numbers, int expected)
        {
            if (GetMaxLengthConsecutiveSequence(numbers) == expected)
            {
                Console.WriteLine(string.Format("{0} passed.", testName));
            }
            else
            {
                Console.WriteLine(string.Format("{0} FAILED.", testName));
            }
        }

        private static void Test1()
        {
            int[] numbers = { 1, 300, 3, 2, 101, 4, 102 };
            int expected = 4;
            Test("test1", numbers, expected);
        }

        private static void Test2()
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            int expected = 5;
            Test("test2", numbers, expected);
        }


        private static void Test3()
        {
            int[] numbers = { 5, 4, 3, 2 };
            int expected = 4;
            Test("test3", numbers, expected);
        }

        private static void Test4()
        {
            int[] numbers = { 1, 3, 2, 4, 5, 19, 18, 17, 16 };
            int expected = 5;
            Test("test4", numbers, expected);
        }

        private static void Test5()
        {
            int[] numbers = { 1, 6, 3, 5, 9, 7 };
            int expected = 3;
            Test("test5", numbers, expected);
        }

        static void Main(string[] args)
        {
            Test1();
            Test2();
            Test3();
            Test4();
            Test5();
        }
    }
}
Success #stdin #stdout 0.04s 33952KB
stdin
Standard input is empty
stdout
test1 passed.
test2 passed.
test3 passed.
test4 passed.
test5 passed.