Dynamic Programming Solution