I'm sorry if this is not the right platform to ask this question. I have been looking for a solution these last two days and I have not been able to find it. Here is the problem:
Design an algorithm that looks for the number of ways you can
Cross N meters by jumping lengths of 1, 2, 3, 4 or 5 meters.
Suppose that N can be a very large number. What is the result
We can use dynamic programming to solve this problem. Let's use n[k] to represent the number of ways to reach the distance k. This distance can be reached by jumping from one of the previous 5 distances. Thus, the number of ways by which we can reach this distance is the sum of the ways by which we can reach the previous 5 distances:
not[k] = n[k-1] + n[k-2] + n[k-3] + n[k-4] + n[k-5]
The solution is simple for the loop.
FUNCTION ways (N)
not = 1
FOR k IN [1..N]
not[k] = 0
FOR IN [1..min(5, k)+1]
not[k] + = n[k – d]
This solution has a time complexity of O (N). But we can have even better performances. The given sum can be represented by a 1×5 matrix of units multiplied by a 5×1 matrix of previous elements. If we use the same approach for moving, we can get relationship B[k] = A * B[k-1], or:
B[k] =[not[not [n[k-4] ][not[not [n[k-3] ][not[not [n[k-2] ][not[not [n[k-1] ][not[not [n[k] ]A = [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1] [1 1 1 1 1]
If b = [0 0 0 0 1]& # 39 ;, [0 0 0 0 1] * B[k] = n[k]. Now, because of B[k] = A * B[k-1], B[k] = A ^ T * B. With that, the solution of our problem can be represented as a relation n[N] = [0 0 0 0 1] * A ^ N * [0 0 0 0 1]"If we use the above-mentioned optimal approach for pow (A, N) computation, this solution has a time complexity O (log N). We must keep in mind that this has a high constant related to this complexity, because the multiplication of the matrix takes time, but for a large enough N, this solution is optimal.
I think this is enough to understand the problem as well as the solution. But I can not understand the problem yet. Since there is no discussion forum about this problem, I can not talk to others about it. An idea or hints? Thank you for your time.
source of this problem: https://www.toptal.com/algorithms/interview-questions