LeetCode 276: Paint Fence Solution

Master LeetCode problem 276 (Paint Fence), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

276. Paint Fence

Problem Explanation

Explanation:

The problem asks us to paint a fence with n posts, and there are k colors to choose from. We need to find the total number of ways to paint the fence such that no more than two adjacent posts have the same color.

To solve this problem, we can use dynamic programming. We can maintain two variables, same and different, to represent the number of ways to paint the current post the same color as the previous post and a different color from the previous post, respectively.

For each post, we can calculate the new values of same and different based on the previous states. The new value of same is equal to the previous value of different because we can only paint the current post the same color as the previous post if the previous post is a different color. The new value of different is the sum of the previous values of same and different multiplied by k-1 because we can paint the current post a different color in k-1 ways.

We iterate through all posts and update the values of same and different accordingly. Finally, the total number of ways to paint the fence is the sum of the final values of same and different.

Time Complexity:

The time complexity of this approach is O(n) where n is the number of posts.

Space Complexity:

The space complexity of this approach is O(1) since we are using only two variables to store the values of same and different.

:

Solution Code

class Solution {
    public int numWays(int n, int k) {
        if (n == 0) return 0;
        if (n == 1) return k;

        int same = 0, different = k;
        for (int i = 2; i <= n; i++) {
            int newSame = different;
            int newDifferent = (same + different) * (k - 1);
            same = newSame;
            different = newDifferent;
        }
        return same + different;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 276 (Paint Fence)?

This page provides optimized solutions for LeetCode problem 276 (Paint Fence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 276 (Paint Fence)?

The time complexity for LeetCode 276 (Paint Fence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 276 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 276 in Java, C++, or Python.

Back to LeetCode Solutions