Longest Consecutive elements

by rishul matta

JavaScript

function consecutive(arr) {
	if (arr.length == 0) {
  	return 0;
  }
	var max = 1;
  var map = {};
  arr.forEach(function(key) {
  	var length = 1;
  	if (map[key]) {
    	//there can be repeated elements
    	return;
    } else {
    	if (map[key-1]) {
      	// pick the sum from previous elemnt
      	 length = map[key-1];
        map[key] = ++length;
      } else {
      	map[key] = length;
      }
      
      while (map[++key]) {
      	// incremenet the counts of all the elements after this insertion
      	map[key] += length;
      }
    }   

  });
  
  for (var prop in map) {
    	if (map[prop] > max) {
      	max = map[prop];
      }
    }
  
  
  return max;
}

//alert(consecutive([ -6, -4, -5, -2, -3 ]))

alert(consecutive([ 100, 4, 200, 1, 3, 2 ]))