Time Complexity of Path Using Dynamic Programming and Memoization
We can see that using matrices for intermediate storage drastically reduces the computation time. The maximizeReward
function fills each cell of the matrix only once, so its time complexity is O(m * n)
. Similarly, the best direction also has a time complexity of O(m * n)
.
The printPath
routine would print the entire path in O(m+n)
time. Thus, the overall time complexity of this path finding algorithm is O(m * n)
. This means we have a drastic reduction in time complexity from O(2) to O(m + n)
. This, of course, comes at a cost of additional storage. We need additional reward
and direction
matrices of size m * n
, making the space complexity O(m * n)
. The stack of course uses O(m+n)
space, so the overall space complexity is O(m * n)
.