HackerEarth Interview Question

A problem on DP