Optimal algorithm for invesment