![]() |
VOOZH | about |
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 the answer can be large, return it modulo 10^9 + 7.
Input : n = 2 k = 4
Output : 16
Explanation: We have 4 colors and 2 posts.
Ways when both posts have same color : 4
Ways when both posts have diff color :4(choices for 1st post) * 3(choices for 2nd post) = 12Input : n = 3 k = 2
Output : 6
The Painting Fence algorithm addresses a common combinatorial problem: Given a fence with n posts, how many ways can you paint the fence with k colors such that no more than two adjacent posts have the same color? This problem can be easily solved using Dynamic Programming.
Algorithm:
Below is the implementation of the above algorithm:
6
Time Complexity: O(N)
Auxiliary Space: O (N)
We can optimize the above solution by use one variable instead of a table.
Below is the implementation of the problem:
6
Time Complexity: O(N)
Auxiliary Space: O(1)