DP/Greedy problem

Can this question be solved using dp . Also can you please explain why greedy works. Thanks.https://codeforces.com/contest/1154/problem/D