Long jumps – Dp problem in C++

Now we will be going to solve a dynamic programming problem Long jumps in C++.

Problem description

A person is currently standing on point 0 in the 1-D array and jumps to reach point N. For integers A and B, He can jump minimum A points and maximum B points. Given three integers N,A,B (1<=A<=B<=N) . Find the number of ways a person standing on point 0 can reach point N (modulo 1e9+7).


1<= N <=200000


N=6 A=2 B=4





It is a dp problem Let dp[i] be the corresponding answer for point i. We can simply observe that for point i, points i-a, i-a-1….i-b will contribute to the answer. So dp[i] = dp[i-a]+dp[i-a-1]…dp[i-b]. We will iterate i from 1 to n to get our corresponding answer. Its time complexity will be O(n^2) Since constraints on N, A, and B are large, the above solution may give Time Limit Exceeded. To calculate dp[i] fast, we can maintain a variable temp which stores value of dp[i-a]+dp[i-a-1]…dp[i-b], and everytime when we increase i, we will subtract dp[i-b-1] and add dp[i-a] to temp.


using namespace std;
#define mod 1000000007
int main(){
    int n,a,b,temp=0;
    for(int i=1;i<=n;++i){
        if(i-a<0) continue;
        if(i-b-1>=0) temp=(temp-dp[i-b-1]+mod)%mod;

Sample case

For given values, N=6, A=2, B=4 it means he can take jumps of 2, 3, and 4 points the answer will be 4. The 4 ways are : 0->2->4->6 , 0->2->6 , 0->3->6 , 0->4->6

Time complexity – O(n) And Space complexity – O(n).

Leave a Reply

Your email address will not be published. Required fields are marked *