Microsoft Interview Question

HackerRank Hard question. Solved it with dynamic programming.