Ok, so that's memoization. In dynamic programming, we get rid of the recursion. So your best function actually does this:
1 2 3 4 5 6
|
int best(int start,int stop) {
if (Best[start][stop]==0) {
Best[start][stop]= max( (sum[stop]-sum[start-1])-Best[start+1][stop],(sum[stop]-sum[start-1])-Best[start][stop-1] );
}
return Best[start][stop];
}
|
Since there is no recursion, we will need to call Best(start,stop) for all start<=stop to fill the array. Something like:
1 2 3 4 5
|
for(int start=1;start!=N;++start) {
for(int stop=start+1;stop!=N+1;++stop) {
Best(start,end);
}
}
|
However, this is clearly rubbish because this will call best(2,7) before it calls best(3,4). Chances are the calculation of best(2,7) will require the calculation of best(3,4), so this will return nonsense. The loops must be done in an order such that everything required for a particular calculation has already been calculated.
If you look at my original code, you will see that I use a different recursion to you, lines 20-28. However, I still have a best, a start, and a stop. This should give you and idea of how to translate between my code and your code.
1 2 3 4
|
N <=> numCoins
start <=> ai+1
stop <=> bi+1
Best[start][stop] <=> states[(start-1)*N+stop]
|
Don't worry that my recursion is different, just concentrate on my for loops. Can you figure out how I make sure that all necessary calculations are done first?