# How to find lists associated with the max ListCorrelate

Suppose I have two lists like this:

list1 = RandomReal[10, RandomInteger[{20, 50}]];
list2 = RandomReal[20, RandomInteger[{20, 50}]];


Now I can find the max correlation between the two lists easily:

ListCorrelate[list1, list2, {-1, 1}, 0] // Max;


But now I want to find the pair of lists associated with the maximum inner product.

At first I used a this way to get what I want:

ClearAll[myListCorrelate];
myListCorrelate[list1_,list2_]:=Block[{Times=List,Plus=List,cor,cor2},
cor=ListCorrelate[list1/.x_?NumericQ:>ToString[x],list2,{-1,1},0];
cor2=ToExpression[Transpose/@(Cases[#,{__}]&/@cor[[2;;-2]])];
cor2[[First@Ordering[Dot@@@cor2,-1]]]
];
myListCorrelate[list1, list2];


This method works fine but it has two major problems:

The first one is that if the lists are long the processing time will be too long.

Second I get from time to time an error about TimeConstrained (I believe this error is generated internally by the kernel function ListCorrelate)

Before programing another method, I thought to ask if there is an easy way or built-in function that can solve this problem.

Is there any easy way to get the lists associated with the max ListCorrelate

Thank you

I am currently using this method which is good and fast:

   ClearAll[myListCorrelate];
myListCorrelate[list1_, list2_] :=
Module[{corr, lag, templist1 = list1, templist2 = list2, n1, n2},
corr = ListCorrelate[list1, list2, {-1, 1}, 0];
lag = First@Ordering[corr, -1] - Length[list1];
If[Positive[lag],
templist1 = Join[ConstantArray[0, Abs@lag], templist1],
templist2 = Join[ConstantArray[0, Abs@lag], templist2]];
If[(n1 = Length[templist1]) < (n2 = Length[templist2]),
templist1 = Join[templist1, ConstantArray[0, n2 - n1]],
templist2 = Join[templist2, ConstantArray[0, n1 - n2]]];
{templist1, templist2}]