# Instructions changesAllowed Answer 0 "UULRRLLL" 1 3 1 "ULDR" 0 1 2 "ULDR" 2 2 3 "ULDRRLRUDUDLURLUDRUDL" 4 8 4 "LRLDRURDRDUDDDDRLLRUUDURURDRRDRULRDLLDDDDRLRRLLRRDDLRU 47 94 RLRULLLLLRRRDULRULULRLRDLLDDLLRDLUUDUURRULUDUDURULULLD RUDUUURRRURUULRLDLRRRDLLDLRDUULUURUDRURRLURLDLDDUUURRU RRLRDLDDULLUDLUDULRDLDUURLUUUURRLRURRDLRRLLLRDRDUUUDRR RDLDRRUUDUDDUDDRLUDDULRURRDRUDLDLLLDLUDDRLURLDUDRUDDDD URLUUUDRLURDDDDLDDRDLUDDLDLURR" 5 "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU 300 150 UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU UUUUUUUUUUUUUUUUUUUUUUUUUUUUUU" 6 "UD" 1 1 7 "UUUUDDLDLRRL" 1 3
My first pertinent observation is that it always takes an even number of moves to get back to point (0,0).
My second pertinent observation is that if you start at (0,0) after executing instruction i, and you want to end at (0,0) after executing instruction j, then you can determine how many instructions you need to change in O(j-i) time. You do that by simply determining where you would be with no changes. Then it's a simple mathematical function.
Take an example -- suppose the moves are "ULUR" and you want to be at (0,0) in four moves. With no changes, you'll be at cell (0,2). If you change one of those U's to a D, then you'll end up at cell (0,0).
Suppose instead that the moves are "ULLR". Then you'll be at (-1,1) after four moves. If you change the U to an R, or if you change an L to a D, then you'll end up at cell (0,0).
I hope that helps you figure out the mathematical function.
Now, to solve this with dynamic programming, we need a recursion. Try this one out: Let M(i,c) be the maximum times that you reach (0,0) if you start at (0,0) after move i, with c changes left. Obviously, M(0,changesAllowed) solves the problem.
When c=0, you can calculate M(i,0) by simply running through the moves and counting how many times you reach (0,0).
To solve M(i,c), you determine how many changes are required to end at cell (0,0) after i+2 moves. Call that number x. If x ≤ c, then the best way for you to solve the problem by returning to cell (0,0) after two moves is 1 + M(i+2,c-x). Next, determine how many changes are required to end at cell (0,0) after i+4 moves. Again, call that number x If x ≤ c, then the best way for you to solve the problem by returning to cell (0,0) after four moves is 1 + M(i+4,c-x). Keep incrementing that value by two until it's too big, and return the maximum answer.
This memoizes pretty easily, and with the memoization, you can solve the problem within the topcoder constraints.
So, let's start with M(0,1):