Algorithm 反转距离

Algorithm 反转距离,algorithm,Algorithm,首先让我们回顾一下反转的定义 一些包含数字的序列S的逆是当S[i]>S[j]和i

首先让我们回顾一下反转的定义

一些包含数字的序列S的逆是当S[i]>S[j]和i
1 4 3 7 5 6 2
我们有以下的反演(4,3),(4,2),(3,2),(7,5),等等

我们将问题陈述如下:反演距离是两个反演值之间的最大距离(就索引而言)。例如,我们可以执行人脑搜索,得到一对(4,2)(S[1],S[6]),其中索引距离为6-1=5,这在这种情况下是可能的最大值

这个问题可以用O(n^2)中的简单方法解决,方法是找到所有的反演并保持最大距离(或者如果我们找到更好的选项,则更新) 我们还可以使用合并排序执行更好的反转搜索,因此在O(nlogn)中也可以执行同样的操作。存在O(n)算法的可能性吗?记住,我们只需要最大距离,我们不想找到所有的倒数。请详细说明。

是的,O(n)算法是可能的

我们可以使用贪婪算法提取严格递增子序列:

source:                          1 4 3 7 5 6 2
strictly increasing subsequence: 1 4   7
然后我们可以向后提取严格递减的子序列:

source:                          1 4 3 7 5 6 2
strictly decreasing subsequence: 1           2
注意,在发现严格递减的子序列后,我们可以将其解释为递增序列(在法线方向)

对于这些子序列的每个元素,我们需要将它们的索引存储在源序列中

现在,通过合并这两个子序列可以找到“反转距离”(类似于OP中提到的合并排序,但只需要一个合并过程):


也许我的想法和@Evgeny一样。 解释如下:

make a strictly increasing array from the beginning we call it array1
make a strictly decreasing array from the ending which is array2 (But keep the values in increasing order)

***Keep track of original indexes of the values of both arrays.

Now start from the beginning of both arrays.

Do this loop following untill array1 or array2 checking is complete

    While( array1[index] > arry2[index] )
    {
        check the original distance between array1 index and arry2 index.
        Update result accordingly.
        increase array2 index.
    }
    increase both array index

Continue with the loop
在这个过程结束时,您将获得最大的结果。这个解决方案的证明并没有那么复杂,你可以自己试试

make a strictly increasing array from the beginning we call it array1
make a strictly decreasing array from the ending which is array2 (But keep the values in increasing order)

***Keep track of original indexes of the values of both arrays.

Now start from the beginning of both arrays.

Do this loop following untill array1 or array2 checking is complete

    While( array1[index] > arry2[index] )
    {
        check the original distance between array1 index and arry2 index.
        Update result accordingly.
        increase array2 index.
    }
    increase both array index

Continue with the loop