How to count the maximum consecutive set of numbers in an array with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class Program
{
	private static int countMaxConsecutiveSetOfNumbers(int[] arr) {
		int size = arr.Length;

		HashSet<int> set = new HashSet<int>();
		
		for (int i = 0; i < size; i++) {
			set.Add(arr[i]);
		}

		int mx = 0;
		for (int i = 0; i < size; i++) {
			if (set.Contains(arr[i])) {
				int temp = arr[i];

				while (set.Contains(temp)) {
					temp++;
				}

				mx = Math.Max(mx, temp - arr[i]);
			}
		}

		return mx;
	}

	public static void Main(string[] args)
	{
		int[] arr = new int[] {22, 3, 21, 32, 24, 31, 4, 99, 23};

		// 21 22 23 24

		Console.Write(countMaxConsecutiveSetOfNumbers(arr));
	}
}




/*
run:
 
4
 
*/

 



answered Oct 22, 2022 by avibootz
...