public class MaxGap {
static class Bucket{
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
}
public static int getMaxGap(int[] array){
int n = array.length, index;
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for(int d : array){
if(d < min)
min = d;
if(d > max)
max = d;
}
int bucketLen = (max - min)/(n-1);
Bucket[] buckets = new Bucket[n-1];
for(int i = 0; i < buckets.length; i++){
buckets[i] = new Bucket();
}
buckets[0].max=buckets[0].min=min;
buckets[n-2].max=buckets[n-2].min=max;
for(int i = 0; i < n; i++){
if(array[i] != min && array[i] != max) {
index = (array[i] - min) / bucketLen;
if (array[i] > buckets[index].max)
buckets[index].max = array[i];
if (array[i] < buckets[index].min)
buckets[index].min = array[i];
}
}
int currGap, maxGap = 0, low = 0, high = 0, preIndex = 0;
for(int i = 1; i < n-1; i++){
if(buckets[i].max != Integer.MIN_VALUE) {
currGap = buckets[i].min - buckets[preIndex].max;
if (currGap > maxGap) {
maxGap = currGap;
low = buckets[preIndex].max;
high = buckets[i].min;
}
preIndex = i;
}
}
System.out.println(low + "-" + high);
return maxGap;
}
public static void main(String[] args){
int[] array = {1,51,2,8,90};
System.out.println(getMaxGap(array));
}
}