It seems greedy algorithm.