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:

  1. We can try to continue with our previous match and check whether it is possible to change $C_i$ in such a way that it matches with $B(j+1)$.
  2. We can start finding a new match from current position and check if $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:

  1. Try to match with the first element of $B$.
  2. For all the lengths of the proper suffix of $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$.

Contributors

Statistics

52% Solution Ratio
c_sharpminorEarliest, Mar '21
steinumFastest, 0.0s
steinumLightest, 5.5 kB
Deshi_TouristShortest, 929B
Toph uses cookies. By continuing you agree to our Cookie Policy.