I have two tables (A, B) and a sum M. I need to find a number from each table that does sum M. If there are not two items which form the sum M, then the nearest solution and the smallest are the sum. See the examples below. What is the effective way to find the solution for this?

```
eg1:
A =(200,300,600,900)
B =(1000,200,300,500)
M = 900
Output : A(2), B(2)
600 from A and 300 from B sums 900.
eg1:
A =(200,300,600,1000)
B =(1000,400,600)
M = 1500
Output : A(3), B(1)
1000 from A and 400 from B sums 1400 which is near to the sum 1500.
```