Skip to content

Commit bd03fdf

Browse files
authored
Create ConstructTheArrayDP
1 parent 83d106d commit bd03fdf

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

ConstructTheArrayDP

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.io.*;
2+
import java.math.*;
3+
import java.security.*;
4+
import java.text.*;
5+
import java.util.*;
6+
import java.util.concurrent.*;
7+
import java.util.regex.*;
8+
9+
public class Solution {
10+
11+
// Complete the countArray function below.
12+
static long countArray(int n, int k, int x) {
13+
14+
final long MOD = 1000000007;
15+
16+
long[] a = new long[n];
17+
long[] b = new long[n];
18+
19+
a[0] = x == 1 ? 1 : 0;
20+
b[0] = x == 1 ? 0 : 1;
21+
22+
//O(n) time and space
23+
for (int i = 1; i < n; i++) {
24+
a[i] = b[i-1] % MOD;
25+
b[i] = (a[i - 1] * (k - 1) + b[i - 1] * (k - 2)) % MOD;
26+
}
27+
28+
return a[n-1];
29+
30+
}
31+
32+
private static final Scanner scanner = new Scanner(System.in);
33+
34+
public static void main(String[] args) throws IOException {
35+
36+
String[] nkx = scanner.nextLine().split(" ");
37+
38+
int n = Integer.parseInt(nkx[0]);
39+
40+
int k = Integer.parseInt(nkx[1]);
41+
42+
int x = Integer.parseInt(nkx[2]);
43+
44+
long answer = countArray(n, k, x);
45+
46+
System.out.println(answer);
47+
48+
scanner.close();
49+
}
50+
}

0 commit comments

Comments
 (0)