# Thread: how to develop dynamic programming solution

1. Member
Join Date
Jun 2013
Posts
2
Rep Power
0

## 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:
Java Code:
```    public static int max(int[] costs, int index, int total, int shares) {
if(index >= costs.length) {
}
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.

2. ## 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•