For example 1, you can turn the ratios in A to distances by multiplying them by two, and the ratios in B to distances by multiplying them by one. Then you'll see four distinct planets.
So what we want to do is multiply the ratios in A by a number a, and the ratios in B by a number b, and then count the number of distinct planets (use a set). The question is, which values of a and b shall we use?
You can answer that by observing that you'll always want to match one planet in A to a planet in B. So what you do is enumerate all of the pairs of A[i] and B[j]. For each of these, set a to B[j] and set b to A[i]. Then the distances of A[i] and B[j] will be equal. You count the number of distinct planets, and then return the minimum of these.
Here's example 3, viewed in that light (make your browser window wider so that everything's on one line).
A[i] = 1 | A[i] = 2 | A[i] = 3 | A[i] = 4 | |
B[j] = 6 | { 6, 12, 18, 24 } ∪ { 6, 7, 8, 9 } = 7 | { 6, 12, 18, 24 } ∪ { 12, 14, 16, 18 } = 6 | { 6, 12, 18, 24 } ∪ { 18, 21, 24, 27 } = 7 | { 6, 12, 18, 24 } ∪ { 24, 28, 32, 36 } = 7 |
B[j] = 7 | { 7, 14, 21, 28 } ∪ { 6, 7, 8, 9 } = 7 | { 7, 14, 21, 28 } ∪ { 12, 14, 16, 18 } = 7 | { 7, 14, 21, 28 } ∪ { 18, 21, 24, 27 } = 7 | { 7, 14, 21, 28 } ∪ { 24, 28, 32, 36 } = 7 |
B[j] = 8 | { 8, 16, 24, 32 } ∪ { 6, 7, 8, 9 } = 7 | { 8, 16, 24, 32 } ∪ { 12, 14, 16, 18 } = 7 | { 8, 16, 24, 32 } ∪ { 18, 21, 24, 27 } = 7 | { 8, 16, 24, 32 } ∪ { 24, 28, 32, 36 } = 7 |
B[j] = 9 | { 9, 18, 27, 36 } ∪ { 6, 7, 8, 9 } = 7 | { 9, 18, 27, 36 } ∪ { 12, 14, 16, 18 } = 7 | { 9, 18, 27, 36 } ∪ { 18, 21, 24, 27 } = 7 | { 9, 18, 27, 36 } ∪ { 24, 28, 32, 36 } = 7 |
The best of these is the one where the union of the two sets is of size 6 (A[i] = 2 and B[j] = 6).