Goldman Sachs interview question

medium level LC- DP/DFS style question