Cost balancing algorithm, implemented in python and javascript