Greedy algorthm not infinite looping