PROBLEM LINKS
DIFFICULTY
EASY
EXPLANATION
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.