20
loading...
This website collects cookies to deliver better user experience
A batsman can score either {1,2,3} runs in a ball. Find the number of ways he can score "X".
static int possibleWaysToReachScore(List<Integer> runs, int x) {
// table[i] will store count of solutions for value i.
int[] table = new int[x + 1];
// Initialize all table values as 0
Arrays.fill(table, 0);
// Base case (If given value is 0)
table[0] = 1;
// One by one consider given runs
// and update the table[]
// values after the index greater
// than or equal to the value of
// the picked move
runs.forEach(
n -> IntStream.rangeClosed(n, x)
.forEach(i -> table[i] += table[i - n])
);
return table[x];
}
given we have 1,2,3 and we want say 10 runs, we start with a dp array which will store all possible ways to get to the index (which represents the runs).
so, naturally table[0]=1
iteration for n = 1
i + (i-1)
iteration for n = 2
i + (i-2)
iteration for n = 3
i + (i-3)
[(0=1), (1=1), (2=2), 3, 4, 5, (6=7), 8, 10, (9=12), 14]