Let $A, B$ be two list of equal length, where $A$ is weakly increasing. For example, $A=[1, 1, 2, 3, 3, 4]$, $B=[12, 9, 10, 15, 15, 14]$.

Define $m_{A,B} = { [ A_i, B_i ] }$ (this is a multi-set of pairs of integers, not a list of pairs, so the order of pairs in $m_{A,B}$ does not matter).

By a result in symmetric group, there is a unique element with maximal length (length of the reduced word) in $S_k$ ($k$ is the length of $A$) such that $m_{A,w(sorted(B))} = m_{A,B}$, where $sorted(B)$ is to sorted B such that it is weakly increasing, and the action of $w=s_{i_1} \cdots s_{i_m}$ on a list $L$ is defined by: $s_j(L)$ means exchanging the jth and j+1th elements of $L$.

There is a method to compute the longest word $w$ by checking all elements in $S_k$. But it takes a long time when $k$ is large. The following function works fine and returns correct result.

```
def LongestPerm(A,Bsorted,B):
k = len(A)
S = set([(A[i],B[i]) for i in range(k)])
W = WeylGroup('A'+str(k-1), prefix = 's')
winner = W.one()
for w in W:
wstr = w.inverse().to_permutation_string()
if set([(A[int(wstr[i])-1],Bsorted[i]) for i in range(k)]) == S:
if w.length()>winner.length():
winner = w
return winner
```

Is there some method to compute $w$ faster (without checking all elements of $S_k$)? Thank you very much.