Thank you for the reply. Yes, using Dynamic Programming solved the issue.