Tuesday, March 29, 2011

amazon question find min diff in a list of int

static private void minDiff(int[] intArray)
{
if (intArray == null)
throw new Exception("minDiff - intArray is null");

var query = intArray.OrderBy(x1 => x1);
List intList = query.ToList();
if (intList.Count <= 1)
throw new Exception("minDiff - must have at least 2 elements in list");

int minDiff = int.MaxValue;
int x = -1;
int y = -1;
for (int i = 1; i < intList.Count - 1; i++)
{
if (intList[i] - intList[i - 1] < minDiff)
{
x = intList[i];
y = intList[i - 1];
minDiff = x - y;
}
}
Console.WriteLine("x=" + x + " y=" + y + " minDiff=" + minDiff);
Console.ReadLine();
}

static private void testMinDiff()
{
int[] intArray = new int[] { 3, 9, 6, 17, 33, 1, 16 };
minDiff(intArray);
}

No comments:

Post a Comment