Skip to content

Instantly share code, notes, and snippets.

@sudipto80
Created January 7, 2016 10:46
Show Gist options
  • Save sudipto80/7ebb91628a2ea678c557 to your computer and use it in GitHub Desktop.
Save sudipto80/7ebb91628a2ea678c557 to your computer and use it in GitHub Desktop.
Longest Consecutive Sequence
int[] nums = {1,6,10,4,7,9,12,11,5,13};
int max = nums.Max ( );
int[] vals = new int[max+1];
for(int i = 0;i<nums.Length;i++)
vals[nums[i]]++;
Dictionary<int,int> lengthMap = new Dictionary<int,int>();
int k=0;
for(k=1;k<vals.Length;k++)
{
if(vals[k-1]==0 && vals[k]==1)//from nothing to something (getting up on the plataeu)
lengthMap.Add(k,1);
if(vals[k]==0 && vals[k-1]==1)//from something to nothing (getting down off the plataeu)
lengthMap[lengthMap.Last ().Key]=k;//marking the end of a sequence
}
//if there are all "ones" towards the end.
if(k==vals.Length && vals[k-1]==1)
lengthMap[lengthMap.Last ().Key]=k;
//This sorting is not required.
//We can keep the differences in a third element
//and thus maintain a list of tuples where the last element is the difference
//Now finding the maximum difference is the longest sequence
KeyValuePair<int,int> longestSeqStartEnd = lengthMap.OrderByDescending (m => m.Value - m.Key).First ();
Console.WriteLine("The longest sequence is ");
for( int i = longestSeqStartEnd.Key;i<longestSeqStartEnd.Value;i++)
Console.WriteLine(i);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment