KatInterview

Cheapest Daily Ticket Plan Without Back-to-Back Repeats

Dynamic ProgrammingAuto-graded · 25 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingpath-reconstructionpaint-house

Last updated

Choose one of three item types each day with no type repeated on adjacent days, minimizing total cost and returning the unique optimal sequence of choices.

A shop offers items in three colors: blue, green and red. You will visit it on each of n consecutive days and must buy exactly one item per day. On day i (0-indexed), the blue item costs blue_costs[i], the green item costs green_costs[i], and the red item costs red_costs[i].

You may not buy the same color on two consecutive days. Find the plan with the smallest total cost and return the color chosen on each day.

Output format

Return a list of n single-character strings, where element i is the color bought on day i:

  • 'b' for blue
  • 'g' for green
  • 'r' for red

Rules

  • For every i from 1 to n - 1, the colors on day i - 1 and day i must differ.
  • The same color may appear again on days that are not adjacent (for example green, red, green is allowed).
  • The input is guaranteed to have exactly one valid color sequence with the minimum total cost, so the expected answer is unique and no tie-breaking is needed.

Constraints

  • The three lists all have the same length n.
  • 1 <= n <= 10^5
  • 1 <= cost <= 10^4 for every entry.
  • The minimum total fits comfortably in a 32-bit signed integer.

Examples

Example 1

Input: cheapest_color_plan([7, 3, 8, 2], [2, 9, 4, 6], [5, 1, 9, 7])

Output: ['g', 'r', 'g', 'b']

Example 2

Input: cheapest_color_plan([1, 2], [2, 100], [3, 100])

Output: ['g', 'b']

Example 3

Input: cheapest_color_plan([5], [3], [4])

Output: ['g']

Hints

Hint 1

Picking the cheapest color each day can fail, because a cheap choice today may force an expensive choice tomorrow. Think about what information about the past actually matters for the next day.

Hint 2

Let the state be the color bought on the current day. For each color, store the cheapest total cost of any valid plan for the days so far that ends in that color; each color extends the best of the other two colors from the previous day.

Hint 3

To recover the sequence rather than just the cost, record for each day and each color which previous color gave the best value. Start from the cheapest final color, follow these records backward, then reverse the result.