Question d’entretien chez Amazon

Solve this using dynamic programming