KatInterview

Booth Assignment Plan: Cheapest Non-Repeating Color Sequence

Dynamic ProgrammingAuto-graded · 21 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingpath-reconstructionarrays

Last updated

Choose one of three colors per day to minimize total cost with no color on two adjacent days, then return the actual sequence using DP with backtracking.

A workshop finishes one product per day for n consecutive days. Each product must be coated in exactly one of three colors: 'slate', 'ember', or 'moss'.

The price of coating the product on day i depends on the color:

  • 'slate' costs slate_price[i]
  • 'ember' costs ember_price[i]
  • 'moss' costs moss_price[i]

Days are indexed from 0. The same color may not be used on two consecutive days.

Write a function that returns the color chosen for every day so that the total price over all n days is as low as possible.

Output format

  • Return a list of n strings. Element i is the color for day i, and must be exactly 'slate', 'ember', or 'moss'.
  • No two neighboring elements may be equal.
  • The sum of the chosen prices must be the minimum over all valid color sequences.
  • The input is guaranteed to have exactly one valid sequence that reaches the minimum total, so no tie-breaking rule is needed.

Constraints

  • 1 <= n <= 10^5, and all three lists have length n.
  • 1 <= price <= 10^4 for every entry.
  • Exactly one valid color sequence achieves the minimum total price.
  • When n == 1, there is no adjacency restriction, so the answer is the single cheapest color.

Examples

Example 1

Input: plan_booth_sequence([1, 1, 1], [3, 5, 7], [4, 6, 4])

Output: ['slate', 'ember', 'slate']

Example 2

Input: plan_booth_sequence([18, 12, 1, 9], [13, 15, 7, 9], [12, 16, 4, 8])

Output: ['moss', 'ember', 'slate', 'moss']

Example 3

Input: plan_booth_sequence([100, 1, 76, 14], [22, 20, 1, 2], [99, 99, 5, 12])

Output: ['ember', 'slate', 'moss', 'ember']

Hints

Hint 1

Picking the cheapest allowed color each day can backfire, because a choice today restricts tomorrow. Think about tracking the best total cost for each possible color on the current day.

Hint 2

Let best[c] be the minimum cost of a valid plan for days 0..i that ends in color c. The value for color c on day i is its price plus the smaller of the two best values for the other colors on day i-1.

Hint 3

To recover the actual colors, store for every day and color which previous color gave the minimum. Start from the cheapest final color and follow these links backward, then reverse the result.