# Finding dynamic programming algorithm

I got a matrix of integers of size $3\times n$. Of each one of the three rows, for each column I got to choose one number, with the restriction that, for each $i$, the numbers chosen in the $i$th and $(i+1)$st rows cannot come from the same column.

The problem asks to make an algorithm such that the summation of all the numbers I've chosen is the minimum possible, has time complexity $O(n)$ and space complexity of $O(1)$.

I know how to do this with dynamic programming, in a more classical way: I calculate the sub-problems, store the results in a matrix of size $3\times n$ until the matrix is complete, then the result is the minimum value of the last row.

The problem is that will have space complexity of size $O(n)$, what I'm not seeing?

• Perhaps I misunderstand. For each column you choose one of the three numbers so the total is minimal? Just choose the smallest in each column seems to be the solution. Unless you have other constraints? – Hendrik Jan May 16 '14 at 23:23
• Yes, silly me. The constrain is that you can't choose two consecutive numbers of the same row. For example, I can't choose from col $1$ the first row, and from col 2, the first row again. – FranckN May 17 '14 at 9:28