fork(4) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Interview_ConsecutiveSequence
  6. {
  7. class Program
  8. {
  9. public static int GetMaxLengthConsecutiveSequence(int[] numbers)
  10. {
  11. HashSet<int> set = BuildHashSet(numbers);
  12. return AnalyzeHashSet(set);
  13. }
  14.  
  15. private static HashSet<int> BuildHashSet(int[] numbers)
  16. {
  17. var set = new HashSet<int>();
  18. foreach(int number in numbers)
  19. {
  20. set.Add(number);
  21. }
  22.  
  23. return set;
  24. }
  25.  
  26. private static int AnalyzeHashSet(HashSet<int> set)
  27. {
  28. int maxCount = 0;
  29. while(set.Count > 0)
  30. {
  31. int number = set.First();
  32. int count = 0;
  33. int toDelete = number;
  34.  
  35. while(set.Remove(toDelete))
  36. {
  37. count++;
  38. toDelete++;
  39. }
  40.  
  41. toDelete = number - 1;
  42. while(set.Remove(toDelete))
  43. {
  44. count++;
  45. toDelete--;
  46. }
  47.  
  48. if(count > maxCount)
  49. {
  50. maxCount = count;
  51. }
  52. }
  53.  
  54. return maxCount;
  55. }
  56.  
  57. private static void Test(string testName, int[] numbers, int expected)
  58. {
  59. if (GetMaxLengthConsecutiveSequence(numbers) == expected)
  60. {
  61. Console.WriteLine(string.Format("{0} passed.", testName));
  62. }
  63. else
  64. {
  65. Console.WriteLine(string.Format("{0} FAILED.", testName));
  66. }
  67. }
  68.  
  69. private static void Test1()
  70. {
  71. int[] numbers = { 1, 300, 3, 2, 101, 4, 102 };
  72. int expected = 4;
  73. Test("test1", numbers, expected);
  74. }
  75.  
  76. private static void Test2()
  77. {
  78. int[] numbers = { 1, 2, 3, 4, 5 };
  79. int expected = 5;
  80. Test("test2", numbers, expected);
  81. }
  82.  
  83.  
  84. private static void Test3()
  85. {
  86. int[] numbers = { 5, 4, 3, 2 };
  87. int expected = 4;
  88. Test("test3", numbers, expected);
  89. }
  90.  
  91. private static void Test4()
  92. {
  93. int[] numbers = { 1, 3, 2, 4, 5, 19, 18, 17, 16 };
  94. int expected = 5;
  95. Test("test4", numbers, expected);
  96. }
  97.  
  98. private static void Test5()
  99. {
  100. int[] numbers = { 1, 6, 3, 5, 9, 7 };
  101. int expected = 3;
  102. Test("test5", numbers, expected);
  103. }
  104.  
  105. static void Main(string[] args)
  106. {
  107. Test1();
  108. Test2();
  109. Test3();
  110. Test4();
  111. Test5();
  112. }
  113. }
  114. }
  115.  
Success #stdin #stdout 0.04s 33952KB
stdin
Standard input is empty
stdout
test1 passed.
test2 passed.
test3 passed.
test4 passed.
test5 passed.