KatInterview

Cheapest Fence Painting With No Matching Neighbors

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingdynamic-programmingmemoizationspace-optimization

Last updated

Color a row of posts from a cost table so no two neighbors match, minimizing total cost, using memoized recursion and a space-optimized bottom-up DP, and recover one optimal coloring.

A fence has H posts in a row, and there are C paint colors. You get an H x C table cost, where cost[i][c] is the price of painting post i with color c. Every post gets exactly one color, and two neighboring posts must never share a color.

Your tasks:

  1. Write a top-down solution (recursion plus memoization) that returns the minimum total price.
  2. Write a bottom-up solution that uses as little extra memory as you can manage.
  3. Besides the minimum price, return one valid coloring that achieves it.
  4. State time and space complexity for C = 3 and for arbitrary C. Explain how to bring the DP working memory down to O(C), and whether you can speed up the per-row transition for large C.
  5. Explain how your code behaves in these edge cases: H = 0, C = 0, C = 1, very large costs, and (optionally) negative costs.

Example

cost = [[17, 2, 17],
        [16, 16, 5],
        [14, 3, 19]]

The minimum total is 10, achieved by colors [1, 2, 1] (2 + 5 + 3).

Be ready to justify why your state is sufficient and to say what your function returns when no valid coloring exists.

Hints

Hint 1

The only rule links a post to the one right before it, so the state needs just two things: the index of the post and the color used by the previous post.

Hint 2

For the bottom-up version, row i of the DP depends only on row i-1, so one array of size C is enough. For each color c you need the cheapest value in the previous row excluding c.

Hint 3

That 'cheapest excluding c' is always the smallest value of the previous row, unless c is the position of that smallest value, in which case it is the second smallest. Track the two best values and the index of the best one. For reconstruction, store those two indices per row and walk backwards.