Imagine you're a decorator tasked with painting a beautiful wooden fence for a neighborhood. The fence consists of n posts arranged in a row, and you have k different paint colors to choose from.
However, there are some aesthetic rules you must follow:
- Every post must be painted exactly one color
- No three or more consecutive posts can have the same color (this would look monotonous!)
Your challenge is to determine: In how many different ways can you paint this fence?
Given two integers n (number of posts) and k (number of colors), return the total number of valid painting arrangements.
Example: With 3 posts and 2 colors (Red, Blue), you could paint: RRB, RBR, RBB, BRR, BRB, BBR - that's 6 different ways!
Input & Output
Visualization
Time & Space Complexity
Single pass through n posts, constant work per post
Only need to track previous two state values, not entire array
Constraints
- 1 โค n โค 50
- 1 โค k โค 105
- No three consecutive posts can have the same color
- Every post must be painted exactly one color