Solving related algorithm problem in Java