Math riddle: the smallest positive possible outcome

puzzle

I spent hours trying to solve this riddle, I got $412-385=27$ as the smallest outcome, does anyone have a way to find the smallest positive outcome and prove it?
The riddle:

You have the digits $1, 2, 3, 4, 5, 8.$
You need to place them in these squares without repeating the same digit twice so that you will get
the smallest positive possible outcome:

enter image description here

Best Answer

If you want a rigorous method, check this. By inserting the digits $x_1, x_2, x_3$ in the top and $x_4, x_5, x_6$ in the bottom, and taking the difference, the result is $$d = 100 (x_1 - x_4) + 10 (x_2 - x_5) + (x_3 - x_6)$$

Since we want $d >0$, we must have $x_1 - x_4 > 0$. To have it as small as possible, we need $x_1 - x_4 = 1$. We do not need to decide them atm. Now, for $x_2 - x_5$, we have no restrictions, since it is not possible to make $d$ negative if $100(x_1 - x_4) > 0.$ Hence, we need to make $x_2 - x_5$ as small as possible, which clearly is done by setting $x_2 = 1$ and $x_5 = 8$. Similarly for $x_3 - x_6$, but we can not choose 1 or 8, so the best option is $x_3 = 2$ and $x_6=5$. Now we could choose $x_1=4$ and $x_4 = 3$ and we get $$d = 412 - 385 = 27$$

In case of your python code, its much simpler to use the formula above for $d$. Something like this (pseudo):

for p in Permutations([1,2,3,4,5,8], size=6):

    d = 100(p[0] - p[1]) + .....
    if (d>0)....
Related Question