How will I solve this using DP?
Since you are interested only in the number of trailing zeroes you need only to consider the powers of 2
, 5
which you could keep in two separate nxn
arrays. So for the array
1 2 3
4 5 6
7 8 9
you just keep the arrays
the powers of 2 the powers of 5
0 1 0 0 0 0
2 0 1 0 1 0
0 3 0 0 0 0
The insight for the problem is the following. Notice that if you find a path which minimizes the sum of the powers of 2 and a path which minimizes the number sum of the powers of 5 then the answer is the one with lower value of those two paths. So you reduce your problem to the two times application of the following classical dp problem: find a path, starting from the top-left corner and ending at the bottom-right, such that the sum of its elements is minimum. Again, following the example, we have:
minimal path for the
powers of 2 value
* * - 2
- * *
- - *
minimal path for the
powers of 5 value
* - - 0
* - -
* * *
so your answer is
* - -
* - -
* * *
with value 0
Note 1
It might seem that taking the minimum of the both optimal paths gives only an upper bound so a question that may rise is: is this bound actually achieved? The answer is yes. For convenience, let the number of 2's along the 2's optimal path is a
and the number of 5's along the 5's optimal path is b
. Without loss of generality assume that the minimum of the both optimal paths is the one for the power of 2's (that is a < b
). Let the number of 5's along the minimal path is c
. Now the question is: are there as much as 5's as there are 2's along this path (i.e. is c >= a
?). Assume that the answer is no. That means that there are less 5's than 2's along the minimal path (that is c < a
). Since the optimal value of 5's paths is b
we have that every 5's path has at least b
5's in it. This should also be true for the minimal path. That means that c > b
. We have that c < a
so a > b
but the initial assumption was that a < b
. Contradiction.
Note 2
You might also want consider the case in which there is an element 0
in your matrix. I'd assume that number of trailing zeroes when the product is 1. In this case, if the algorithm has produced a result with a value more than 1 you should output 1 and print a path that goes through the element 0
.