Microsoft interview question

HackerRank Hard question. Solved it with dynamic programming.