Very clean explanation. Thank you so much. Here is my version of the same program with comments:

public int numWays(int n, int k) { if (n <= 0 || k <= 0) { return 0; } if (n == 1) { return k; } // Case 1: First 2 posts have same color. int sameCase = k; // Case 2: First 2 posts have different colors. int diffCase = k * (k - 1); for (int i = 3; i <= n; i++) { int temp = diffCase; /** * To every sameCase and diffCase we can add a new post with different color as the last one. We have k-1 color * options for the last one. */ diffCase = (sameCase + diffCase) * (k - 1); /** * To every diffCase we can add a new post with the same color as the last one to not generate violation - no * more than 2 adjacent fence posts have the same color. */ sameCase = temp; } return sameCase + diffCase; }Paint Fence