HackerEarth interview question

A problem on DP