an algorithm problem ,code and explain