'Python Algorithm To Match Similar Numbers on Array

So I am looking to create a python algorithm and need some guidance going the right path as I can't wrap my head around how to do this.

Say I have an array that looks something like this:

[500, 300, 100, 200, 300,
 600, 400, 200, 50, 100, 
 550, 350, 100, 100, 200]

What I want is for the algorithm to return the best possible combination of similar numbers and arrange them in a row, but here is the trick. The first number needs to stay the first, second second, and third through six get added to together to match the first two but can be moved individually. So the result should be something like this:

[500, 300, 100, 200, 100,
600, 400, 200, 50, 300,
550, 350, 100, 100, 200]

I don't even know if that's the best possible combination but it only required two moves. And the numbers (adding the last three together) are somewhat close:

[500, 300, 400,
[600, 400, 550,
550, 350, 400]

No idea on how I can approach this? Any guidance?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source