Between one configuration and the next, the stack differs at most in the two rightmost elements and the remaining input differs at most in that it loses its leftmost element.
all but a constant number of values of score(i, j, q) and score (i, j) can be reused, to make the time complexity closer to constant time for each calculation of the optimal step.