First implementation, greedy algorithm