I made an algorithm that returns the minimum value between two distances in a given array. I would like to know if there is still some way to improve the algorithm by looking at complexity O (N * log (N)). Below the statement.
Write a function that, given an array A non-empty with index zero consists of integers N, returns the minimum distance between the indices of this matrix that have adjacent values. The function should return -1 if the minimum distance is greater than 100 million. The function should return -2 if there are no adjacent indexes.
Assume this:
N is an integer within the range [1..40,000];
Each element of array A is an integer within the range
[- 2,147,483,648..2,147,483,647]
Complexity:
expected worst case time complexity is O (N * log (N));
expected worst-case complexity space is O (N), in addition to the input storage (not
public static int solution(int[] A)
{
int resultado = int.MaxValue;
if (A.Length < 2 || A == null)
return -2;
for (int i = 0; i < A.Length - 1; i++)
{
for (int j = i + 1; j < A.Length; j++)
{
if (Math.Abs(A[i] - A[j]) < resultado)
resultado = Math.Abs(A[i] - A[j]);
}
}
if (resultado > 100000000)
return -1;
return resultado;
}