Pregunta de entrevista de Microsoft

HackerRank Hard question. Solved it with dynamic programming.