building table and using greedy algorithm