Getting run error

I am getting run error for this problem. Only one test case passes correctly. I checked the solution provided but not able to understand.

1 Like

@mr.dheeraj000,

You have to use dynamic programming in this question. Your recursion approach is correct but since the test cases are large it will run out of memory and throw a run error.

@mr.dheeraj000

You have not took the modulo 10^9 + 7

Updated code link in my previous. comment, please find it !

Regards,
-@rkrishna

I hope that was getting correct! and should have passed all the test cases!

If you have no further doubts " mark it as resolved";
thanks

@Rahul I tried your solution still getting same.

use (int)Math.pow(10,9) + 7 instead of 10^9+7

@sanchit.bansal06 Can you provide the solution I have not done dynamic programming yet!

I tried this but now working!!

@mr.dheeraj000,
I can’t provide you the code. What I can suggest is that you first go through the dynamic programming section and then come back to solve this question. Or you can give it a try without using recursion, I will help you out in case you are not able to understand :smile:

okay! Let me try first.

DP is easy when you have formalized the problem
In this case formalized formula is f(n) = f(n-1) + f(n-m)
So,

  1. Declare an array of size n, let say dp[n] (if 1 -indexed)
  2. From dp[1] to dp[m-1] initiate dp[i] =1
  3. From dp[m] to dp[n] formulate dp[n]=dp[n-1] + dp[n-m]

Print dp[n]
Note: be cautious if n is less than m, in that case just return 1

import java.util.*;
public class Main {
public static int findwaytotiles(int n , int m)
{
if(n<m)
return 1;
int[] dp=new int[n+1];
for(int i=0;i<m;i++)
{ dp[i]=1;

	}
	for(int i=m ;i<=n;i++)
	{
		dp[i]=dp[i-1]+dp[i-m];
		dp[i]=dp[i]%1000000007;
	}
	return dp[n];
}
public static void main(String args[]) {
	Scanner sc= new Scanner(System.in);
	int test= sc.nextInt();
	while(test>0)
{
	int n=sc.nextInt();
	int m =sc.nextInt();
	int result=findwaytotiles(n , m);
	System.out.println(result);
	test--;
}
}

}

I tried this and it worked thanks @rkrishna @sanchit.bansal06 :blush:

As you seem to be happy !:blush:
Click “Mark as resolved” and rate us!

Regards-@rkrishna