# how to develop dynamic programming solution

• 01-23-2014, 07:47 AM
stevenlin598
how to develop dynamic programming solution
I apologize if this question is too broad. I can often write a recursive backtracking solution, but don't know how to cache the answers into an appropriate array.
For example:
Code:

```    public static int max(int[] costs, int index, int total, int shares) {         if(index >= costs.length) {           return total;         }         int buy = max(costs, index + 1, total - costs[index], shares + 1); // buy one stock         int sell = max(costs, index + 1, total + shares * costs[index], 0); // sell all stocks         return Math.max(total, Math.max(buy, sell)); // compares between buy, sell, and doing nothing     }```
This is a dynamic programming exercise, but I have no idea what dimensions the dp array should be (I was thinking maybe dp[index][total][shares], but that seemed like overkill). Is this just because my understanding of recursion isn't solid enough or am I missing something else? This applies to every dp problem I try to solve, so general advice would be helpful.
• 01-23-2014, 03:58 PM
KevinWorkman
Re: how to develop dynamic programming solution
We can't give you general advice, as the dimensions of the array depend entirely on the problem you're trying to solve. What does this method do? What does the array represent? You have to understand what the algorithm is doing before you can use it.