Painting the Fence
Medium Accuracy: 48.89% Submissions: 17705 Points: 4

Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color. Since answer can be large return it modulo 10^9 + 7.

Example 1:

Input:
N=3,  K=2
Output: 6
Explanation: We have following possible combinations:

Example 2:

Input:
N=2,  K=4
Output: 16


Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countWays() that takes n and k as parameters and returns the number of ways in which the fence can be painted.(modulo 109 + 7)

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

Constraints:
1 ≤ N ≤ 5000
1 ≤ K ≤ 100

We are replacing the old Disqus forum with the new Discussions section given below.