diff --git a/README.md b/README.md index ae20685..2afca60 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ easily understandable algorithms for learning purposes. * [Square Subsequences](hacker-rank/algorithms/dynamic-programming/square-subsequences) * [Stock Maximize](hacker-rank/algorithms/dynamic-programming/stock-maximize) * [Summing Pieces](hacker-rank/algorithms/dynamic-programming/summing-pieces) + * [Construct the Array](hacker-rank/algorithms/dynamic-programming/construct-the-array) - [Graph Theory](hacker-rank/algorithms/graph-theory) * [BFS: Shortest Reach](hacker-rank/algorithms/graph-theory/bfs-shortest-reach) * [Crab Graphs](hacker-rank/algorithms/graph-theory/crab-graphs) diff --git a/hacker-rank/algorithms/dynamic-programming/construct-the-array/README.md b/hacker-rank/algorithms/dynamic-programming/construct-the-array/README.md new file mode 100644 index 0000000..706ac11 --- /dev/null +++ b/hacker-rank/algorithms/dynamic-programming/construct-the-array/README.md @@ -0,0 +1,3 @@ +# README + +[https://www.hackerrank.com/challenges/construct-the-array/problem](https://www.hackerrank.com/challenges/construct-the-array/problem) diff --git a/hacker-rank/algorithms/dynamic-programming/construct-the-array/main.cpp b/hacker-rank/algorithms/dynamic-programming/construct-the-array/main.cpp new file mode 100644 index 0000000..905b955 --- /dev/null +++ b/hacker-rank/algorithms/dynamic-programming/construct-the-array/main.cpp @@ -0,0 +1,52 @@ +#include + +using namespace std; +typedef long long ll; +#define mod 1000000007 + +ll power(ll x, ll y) +{ + ll res = 1; // Initialize result + + x = x % mod; // Update x if it is more than or + // equal to p + + while (y > 0) + { + // If y is odd, multiply x with result + if (y & 1) + res = (res*x) % mod; + + // y must be even now + y = y>>1; // y = y/2 + x = (x*x) % mod; + } + return res; +} +// Complete the countArray function below. +ll countArray(ll n, ll k, ll x) { + // Return the number of ways to fill in the array. + if(n == 2){ + if(x == 1) + return 0; + return 1; + } + ll a = power(k - 1, n - 2) - countArray(n - 1, k, x); + a = (a + mod) % mod; + return a; + +} + +int main() +{ + + ll n,k,x; + cin >> n >> k >> x; + + ll answer = countArray(n, k, x); + + cout << answer << "\n"; + + return 0; +} +