Google Interview Question

Graphs and DP mostly with some twists