```python
def count_no_of_ways(n, k):
    """
    Calculates the number of ways to paint a fence with n posts and k colors
    such that at most two adjacent posts have the same color.
    """
    if n == 0 or k == 0:
        return 0

    if n == 1:
        return k

    # Initialize DP variables for n=2 posts.
    # same_count: Number of ways where the last two posts have the same color.
    # For n=2, this means post 1 and 2 are the same.
    # There are k choices for the color.
    same_count = k

    # diff_count: Number of ways where the last two posts have different colors.
    # For n=2, this means post 1 and 2 are different.
    # k choices for post 1, and k-1 choices for post 2.
    diff_count = k * (k - 1)

    # Iterate from the 3rd post up to the n-th post.
    for _ in range(3, n + 1):
        # Store the counts for the previous number of posts (i-1).
        prev_same_count = same_count
        prev_diff_count = diff_count

        # Calculate same_count for the current number of posts (i).
        # If posts i and i-1 are the same, then posts i-1 and i-2 must be different
        # to avoid three consecutive same-colored posts.
        # The number of ways for this is the previous diff_count.
        same_count = prev_diff_count

        # Calculate diff_count for the current number of posts (i).
        # If post i is different from post i-1, the first i-1 posts
        # can be in any valid configuration.
        # The total ways for i-1 posts is the sum of its same and diff counts.
        # Post i has k-1 color choices (any color except the one on post i-1).
        total_prev = prev_same_count + prev_diff_count
        diff_count = total_prev * (k - 1)

    # The total number of ways for n posts is the sum of the two cases.
    return same_count + diff_count
```