Search code examples
optimizationdynamic-programmingpseudocode

How to make correct function in dynamic programming


I have the following problem in dynamic programming.

A person has time machine and he can move in time either 1 year or 2. At the beginning he is at year 0 and he wants to reach year 100. Every step he does (1 or 2 years) he is paying some fixed fees. There is an array with 100 integers represents the fee he needs to pay if he went threw the specific year.

I need to find the minimum amount the person can pay to go from year 0 to year 100 using dynamic programming.

From what i have done so far i think that there should be something like

minCost(i) = min{A[i-1], A[i-2]}

and the base cases are years 1 and 2 which costs A[1], A[2] respectively. But i think this approach has more of greedy algorithm rather than dynamic programming.

I saw the bin packing algorithm of dynamic programming and i understood it and the matrix that represents it.

How should the matrix of the shown problem above look like?

And how should i build the function and the pseudo code for this problem?


Solution

  • You are almost there.

    Think about how will you reach the i th year from i-1 th year and i-2 th year. There is a fee which you are forgetting to take into consideration.

    MinCostToReachYear(i) = min( MinCostToReachYear(i-1) + fee(i-1), MinCostToReachYear(i-2) + fee(i-2) )

    You already know the base cases year 1 and year 2. Can you think of extrapolating with the use of a for loop or more easily with a recursive function which you already know as mentioned above? I leave it as an exercise for you.