Jumping stones

There are n stones in a row from left to right. You are standing on the first stone. From every step from stone number i, you can jump at most k stones further (i+1, i+2, , i+k). You cannot jump over stone number n. How many ways are there to travel to stone number n?

Example:

Input:  n=5, k=2 
Output: 5

Approach

Java

public class JumpingStones {
    public static void main(String[] args) {
        int n = 5;
        int k = 2;
        long[] dp = new long[n + 1];

        dp[1] = 1;

        for (int i = 2; i <= n; i++) {
            long val = 0;
            for (int j = i - 1; j > 0 && i - j <= k; j--) {
                val += dp[j];
            }

            dp[i] = val % 1000000007;
        }

        System.out.print(dp[n]);
    }
}


No comments:

Post a Comment