I wrote a recursive relation as follow :
toss(n, c, m) = toss(n-1, c+1, max(c+1,m)) + toss(n-1,0,m)
n = number of tosses left
c = consecutive heads
m = max number of consecutive heads that have occurred till now
I wrote a dp solution for this problem and have checked the answers on
http://www.udebug.com/UVa/10328. The solution is correct, but I get TLE on the judge
The max runtime of the solution would be n * c * m which is 10^6 operations at max. I cannot understand why I get TLE ?
I have attached my code below :
Code: Select all
import java.util.Scanner;
import java.math.BigInteger;
class Main {
public static int k;
public static BigInteger[][][] memo = new BigInteger[110][110][110];
public static BigInteger minusOne = BigInteger.ZERO.subtract(BigInteger.ONE);
public static BigInteger toss(int n, int c, int m) {
if (n == 0) {
if (m >= k) {
return BigInteger.ONE;
} else {
return BigInteger.ZERO;
}
}
if (!minusOne.equals(memo[n][c][m])) {
return memo[n][c][m];
}
BigInteger ans = BigInteger.ZERO;
ans = ans.add(toss(n - 1, c + 1, Math.max(c + 1, m)));
ans = ans.add(toss(n - 1, 0, m));
memo[n][c][m] = ans;
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
while (sc.hasNextInt()) {
n = sc.nextInt();
k = sc.nextInt();
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
for (int l = 0; l <= n; l++) {
memo[i][j][l] = minusOne;
}
}
}
System.out.println(toss(n, 0, 0));
}
}
}