How to find the minimum number of steps in CodeForces 805D problem?