查找数组相邻元素之间的最大距离

Pra*_*hra 1 c# arrays

我有一个整数数组 say int[] Arr={1, 4, 7, 3, 2 }。现在相邻的边意味着 2 个连续的数字(不是数组的数字系统),即 1、2 是相邻的。我写了几行代码请帮我找出缺点并优化它。

    static void Main(string[] args)
    {
        int[] arr = { 1, 4, 7, 3, 2 };
        Console.WriteLine("adjacent indices with maximum value is {0}",Solution(arr));
        Console.ReadLine();
    }

    static int Solution(int[] arr)
    {
        int maxDistance = -1;
        int newMaxDistance = 0;
        int a = 0, b = 0;

        for (int i = 0; i < arr.Length; i++)
        {
            a = arr[i];
            if (i < arr.Length - 1)
            {
                b = arr[i + 1];
            }

            for (int j = i + 1; j < arr.Length; j++)
            {

                if (arr[j] < b && arr[j] > a)
                {
                    maxDistance = j - i;
                }
                else
                {
                    newMaxDistance = j - i;
                }
            }
        }
        if (newMaxDistance > maxDistance)
        {
            maxDistance = newMaxDistance;
        }
        return maxDistance;


    }
Run Code Online (Sandbox Code Playgroud)

use*_*264 5

将每个元素转换为一对(值,位置),例如 {1,4,7,3,2} -> {(1,0),(4,1),(7,2),(3,3) ,(2,4)}。然后按值对对进行排序:{(1,0),(2,4),(3,3),(4,1),(7,2)}。然后遍历数组,每次看到两个连续的整数时,计算它们位置之间的差异。