Mastercard interview question

DP based problem(medium-hard) in first round.