First of all, think when will an element of $B$
will match with an element of $C$
? An element $C_i$
can be matched with an element of $B_j$
only if $A_i$
divides $B_j$
. (How? Let, $K = B_j / A_i,$
then $A_i$
can be added $(K-1)$
times with $C_i$
to make it $B_j$
)
Now, we need to change every element of $C$
in such a way that it maximizes the number of segments where it matches with the array $B$
. Suppose, we have already matched $j$
elements from array $B$
and we are at position $i$
in the array $C$
. So what can we do now? We have the following two options:
$C_i$
in such a way that it matches with $B(j+1)$
.$C_i$
can be changed into the first element of array $B$
.If the number of match becomes $M$
at some point, then we know we have found a matching segment and increment count by one. From this position we can do the followings:
$B$
.$B$
which is also a prefix of $B$
, can be considered as already matched. (Why? Suppose, $B = [1, 2, 3, 1, 2]$
. Here, its proper suffix which is also a prefix is $[1,2]$
and since we have completely matched with the elements of array $B$
, we can say that the proper suffix has already been matched for our new consideration)We can apply Dynamic Programming to do these efficiently. Let, $dp_{(i,j)}$
where '$i$
' indicates the current position in $C$
and '$j$
' indicates number of already matched positions of array $B$
.