Frage im Vorstellungsgespräch bei Microsoft

HackerRank Hard question. Solved it with dynamic programming.