I have written following code to find the minimum difference from a list of numbers.
Because I am using a loop once and LINQ again to find the minimum, the algorithm is O(N2).
Can you please tell me if I am using the framework in the most optimal way (speed and memory utilisation) to achieve this task:
using (StreamReader sr = new StreamReader("IN.in"))
using (StreamWriter sw = new StreamWriter("OUT.out"))
{
int T = int.Parse(sr.ReadLine());
for (int i = 1; i <= T; i++)
{
int N = int.Parse(sr.ReadLine());
List<int> intList = sr.ReadLine().Split(' ').Select(e => int.Parse(e)).ToList();
intList.Sort();
List<int> diff = new List<int>();
int leastDiff = int.MaxValue;
for (int k = 0; k < intList.Count - 1; k++)
{
int iDiff = intList[k + 1] - intList[k];
diff.Add(iDiff);
leastDiff = Math.Min(leastDiff, iDiff);
}
sw.WriteLine(leastDiff);
}
}
Benchmark
For 3 test case of 5 integers in each list where as for loop implementation takes 55±5 ms. Mr.Mindor LINQ implementation timing varies from 60±50 ms. Memory usage in both implementation is almost 8.3MB
IDisposable
types (StreamReader
andStreamWriter
) inusing
blocks and get rid of the need to callClose()
explicitly. \$\endgroup\$