almost finished greedy algorithm