Here's an idea. Not sure if it is optimal but it should be correct.
- sort each set.
- pop the smallest item from each set into a minheap
- track the max - min of elements in the heap
- repeat:
- pop min from heap
- replace it the next smallest item from the same set (pop min from set again)
- (if said set is empty, stop. you've reached the optimal answer)
of course, you'd insert tuples of (value, parent_set) into the heap so you know which value came from which set once they're popped from the heap and needs to be replaced