Maximum gap problem.
Given n real numbers, find the maximum difference between these n real numbers on the number axis and design a linear time algorithm to solve the maximum gap problem.
There are a lot of codes on the Internet, but no illustrations. I drew a few pictures to help understand.
Code Blocks run code:
#include <stdio.h>
#define INF 1<<30
struct node{
double left,right;
double max=-INF,min=INF;
int index=0;
}x[105];
int main()
{
int i,j;
int n;
double arr[105],max=-INF,min=INF;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%lf",arr+i);
if(max<arr[i])
max=arr[i];
if(min>arr[i])
min=arr[i];
}
double len = (max-min)/(n-1);
x[0].left=min;
x[0].right=min+len;
for(i=1;i<n-1;i++)
{
x[i].left = x[i-1].right;
x[i].right = x[i].left + len;
}
for(i=0;i<n;i++)
{
int temp = (arr[i]-min)/len;
if(temp>=n-1)
temp=n-2;
x[temp].index++;
if(arr[i] > x[temp].max)
x[temp].max=arr[i];
if(arr[i] < x[temp].min)
x[temp].min = arr[i];
}
double Max = -INF;
for(i=1;i<n-1;i++)
{
if(x[i].min==INF)
x[i].min = x[i-1].max;
if(Max<x[i].min - x[i-1].max)
Max = x[i].min - x[i-1].max;
if(x[i].max==-INF)
x[i].max=x[i].min;
}
printf("%lf\n",Max);
return 0;
}