I have great trouble doing recursion, especially trying to visualize it. A great example is the aging wine problem described in the top answer of this link: https://www.quora.com/Are-there-any-good-resources-or-tutorials-for-dynamic-programming-besides-the-TopCoder-tutorial. In the example, you are tasked with finding the optimal sequence of wine to sell given the wine's initial prices and the fact that the prices double each year.
int p[N]; // read-only array of wine prices
// year represents the current year (starts with 1)
// [be, en] represents the interval of the unsold wines on the shelf
int profit(int year, int be, int en) {
// there are no more wines on the shelf
if (be > en)
return 0;
// try to sell the leftmost or the rightmost wine, recursively calculate the
// answer and return the better one
return max(
profit(year+1, be+1, en) + year * p[be],
profit(year+1, be, en-1) + year * p[en]);
}
Above, I have a hard time visualizing. First I think what the function returns at the end of the recursion, which is a 0, then I try to calculate the value that is returned from the second to last recursion. I can do this for several steps until I get lost.
be
anden
? Do you mean begin and end? Why are you multiplying a year by a price? – candied_orange Jul 16 '16 at 01:31