Problem Description
Given n fence posts and k different colors, determine the number of ways to paint the fence such that each post is painted exactly one color and no three consecutive posts have the same color.
Key Insights
- Use dynamic programming to break the problem into subproblems.
- Define two states:
- Ways ending with two posts of the same color.
- Ways ending with two posts of different colors.
- The transition for the "same" state is only possible if the previous state ended with two different colors.
- The "different" state can be achieved by painting a new color that is different from the previous post in both states.
- The final answer is the sum of these two states.
Space and Time Complexity
Time Complexity: O(n) – We compute the result by iterating through each post. Space Complexity: O(1) – Only a fixed number of variables are used for state transitions.
Solution
The strategy is to simulate the painting process post by post while tracking two values:
- same: Number of ways where the last two posts are painted with the same color.
- diff: Number of ways where the last two posts are painted with different colors.
For the first post, the total ways is k. For the second post:
- same = k (each pair where both posts get the same color),
- diff = k * (k - 1) (different colors for first and second post).
For posts from the third onward, update by:
- same[i] = diff[i-1] because only a configuration that ended with two different colors can add a post with the same color as the previous one.
- diff[i] = (same[i-1] + diff[i-1]) * (k - 1) since any valid configuration can add a different color post.
By iterating up to n, the final result will be same + diff.