How can we solve it. Either greedy or dynamic programming. Can we use both? Please provide code also if possible.