helloIamCristiano's blog

By helloIamCristiano, history, 2 years ago, In English

Given 2 arrays A and B of size m and n respectively. The array A is extended by concatenating n copies of A to itself and array B is extended by concatenating m copies of B to itself, thus the new size of each array is m*n. Find the sum abs(A[i]-B[i]) for i from 0 to m*n-1.

Constraints :-
A[i], B[i] <= 50 and Length of the arrays A, B < 1e5

  • Vote: I like it
  • -10
  • Vote: I do not like it

| Write comment?
»
2 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

It is pretty clear that if $$$n = m$$$, you just add $$$n \cdot |A_{i} - B_{i}|$$$. If you've tried writing the operations down on paper, then, the other case should also be fairly obvious. Assume WLOG $$$m < n$$$, then, for each element in $$$A$$$, you must add $$$\sum_{j=1}^{m}|A_{i} - B_{j}|$$$. You can optimize the sum by using prefix sums.

Here I have assumed $$$n$$$ to be the size of array $$$A$$$, and $$$m$$$ for $$$B$$$

  • »
    »
    2 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    How are you using prefix sum here exactly? As we require sum of differences of absolute values, won't the prefix sums be different for each $$$A_{i}$$$

»
2 years ago, # |
  Vote: I like it +3 Vote: I do not like it

For each element in $$$A$$$, you can find the set of indices it ,matches to in $$$B$$$. This set will be same for all $$$A_i$$$ where $$$i = k . gcd(n,m)$$$ and disjoint from other indices. Then you just sort and use prefix sums + binary search for the value at each index of $$$A$$$.