What matters in the calculation is the initial and final positions. If the masses move about while they are being put into place, this does not matter. It makes no difference whether $m$ moves towards $M$, or the other way round, or both move toward each other. The PE only depends on their initial and final separations. Also, because gravity and electrostatic forces are conservative, it does not matter in what order you put the masses into position, or what route you take to get them there. You can choose whatever order and route are easiest for your calculation. When there are more than 2 masses or charges, you can make use of the **Superposition Principle** : the potential energy of the system is the sum of the potential energies of each pair of objects considered in isolation. Start with any one object (1). Then calculate the potential energy between it and each of the other objects (2, 3, 4, ...), getting $W_{21}, W_{31}, W_{41}, ...$. Then do the same for object 2, ignoring object 1, and getting $W_{32}, W_{42}, W_{52},...$ for the potential energies of each pair. Each time you ignore the objects numbered lower, so that you don't count any pair of objects more than once. Finally add all the energies together to get the potential energy of the whole configuration of masses or charges : $$W=W_{21}+W_{31}+W_{41}+... W_{32}+W_{42}+W_{52}+...W_{43}+W_{53}+W_{63}+...$$ For a system of $n$ objects there are $\frac12n(n-1)$ distinct pairs of objects, so there are this many terms to add together.