It is easy to see that in order to make the least number of stops, one should cover as much distance as possible each time. We can compute this in linear time, by maintaining two pointers p1 and p2 such that a[p2] - a[p1] <= M, but a[p2+1] - a[p1] > M. We can decrement p1 and adjust p2 accordingly.
Thus we get get for each point i, dp[i], which is the minimum number of steps to reach the destination from location i. To count the number of ways, we have dp[i] = sum dp[j], such that dp[j] = dp[i+1], and a[j] - a[i] <= M. We can easily compute the dp[] array in linear time as well.
So if the
input is
5 6
0
4
5
6
10
Would the array dp={4,2,2,1,1}?
or array dp={3,1,1,1}?
In the above explanation:
“Thus we get get for each point i, dp[i], which is the minimum number of steps to reach the destination from location i.”
Does dp[i] show us the minimum number of steps from i to destination or the number of ways from i to destination?
We can make two dp. one for storing the minimum possible jumps to reach ith station and other the number ways to reach ith station. Both of the dp at ith station will be updated by the dp of previous stations having distance between them <=m. We can easily do it in O(n^2) by iterating backwards at each i. But by using two pointers we can maintain a boundary till which we’ve to iterate backwards at each i. Also note that the second dp will be sum of no. of ways to reach stations having distance <=m and dp1[i] == dp1[l] i.e. stations having minimum no. of steps to reach.