Daily Vendor Booking with No Immediate Repeats
Dynamic ProgrammingAuto-graded · 18 test casesLast updated
Choose one vendor per day to minimize total price with no vendor on consecutive days, returning the plan with a fixed tie-break; tests DP, backtracking, and best/second-best.
A café books exactly one vendor every morning from a fixed list. Each vendor quotes a price for each day, and prices may differ from day to day. The café has one fairness rule: the same vendor may not be booked on two consecutive days. A vendor may be booked again after a gap of at least one day.
You are given a table prices, where prices[d][v] is the cost of booking vendor v on day d. Both days and vendors are numbered from 0. Find the cheapest valid plan and return its total cost together with the plan itself.
Task
Implement a function that takes prices and returns a pair (total, plan):
totalis the minimum possible sum ofprices[d][plan[d]]over all daysd, taken over all valid plans.planis a list ofn = len(prices)integers, whereplan[d]is the vendor index booked on dayd.- A plan is valid when
plan[d] != plan[d + 1]for everydfrom0ton - 2.
Tie-breaking rule
Several valid plans may share the minimum total. Return exactly one of them, chosen as follows. Compare the tied plans by their last-day vendor and prefer the smaller index. If still tied, compare the second-to-last day and prefer the smaller index, then the third-to-last day, and so on. In other words, among all minimum-cost valid plans, return the one that is lexicographically smallest when the plan is read from the last day back to the first day.
Special cases
- If
n == 1, return the cheapest vendor on that single day. On equal prices, take the smallest index. - If
pricesis empty, return(0, []). - If there is only one vendor (
k == 1), the "no consecutive repeat" rule cannot be satisfied forn > 1. In that case, ignore the rule and return(sum of all prices, [0] * n).
Efficiency
The number of vendors k can be as large as 100, and n as large as 100000, so aim for O(n * k) time rather than O(n * k^2).
Constraints
0 <= n <= 10^5, wheren = len(prices)1 <= k <= 100, wherek = len(prices[d]); every row has the same length1 <= prices[d][v] <= 10^4- The returned value is a pair
(total, plan)withtotalan integer andplana list of integers.
Examples
Example 1
Input: cheapest_vendor_rotation([[4, 2, 7], [3, 1, 5], [6, 8, 2], [5, 4, 9]])
Output: [11, [1, 0, 2, 1]]
Example 2
Input: cheapest_vendor_rotation([[10, 3, 8, 6], [2, 9, 4, 7], [5, 1, 6, 3]])
Output: [6, [1, 0, 1]]
Hints
Hint 1
Only the vendor used yesterday restricts today's choice, so define the state as (day, vendor booked that day) holding the cheapest cost of the prefix ending that way.
Hint 2
To make each day O(k), you do not need to scan every previous vendor for every current one. Which previous-day values can ever be the best predecessor?
Hint 3
Keep the smallest and second-smallest previous-day totals, ranking by (total, vendor index). Use the smallest unless it is the same vendor, in which case use the second smallest. Store the chosen predecessor, then walk back from the best last vendor (smallest total, ties by smaller index).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Only the previous day's vendor affects today's options, so a small DP works. Let dp[d][v] be the cheapest total for days 0..d when vendor v is booked on day d:
dp[0][v] = prices[0][v]dp[d][v] = prices[d][v] + min(dp[d-1][p] for p != v)
The answer is the minimum of dp[n-1][v] over all v.
Speeding up from O(n·k²) to O(n·k)
Scanning all p != v for each v costs O(k²) per day. But for any v, the best predecessor is the vendor with the overall smallest dp[d-1] value, unless that vendor is v itself, in which case it is the vendor with the second-smallest value. So each day we find the best and second-best previous entries once (O(k)), then fill the new row in O(k).
Rebuilding the plan
For each (day, vendor) we store which previous vendor achieved the minimum. After the last day we choose the final vendor with the smallest total (ties by smaller index) and walk the stored pointers backward to recover the plan.
Tie-breaking
Entries are ranked by (value, vendor index), so the best and second-best prefer the lower index on equal cost. The predecessor of (d, v) is therefore the lowest-index vendor p != v among those with minimal dp[d-1][p]. These are exactly the predecessors that can still lead to an optimal plan. Choosing the lowest index at every step while walking backward, starting from the lowest-index optimal last vendor, yields the plan that is lexicographically smallest when read from the last day backward.
Special cases
An empty table gives (0, []). With a single vendor the rule cannot be honored for more than one day, so the specified fallback returns the sum of all prices and a plan of zeros. With n == 1 the loop is skipped and the cheapest vendor, with the smallest index on ties, is returned.
Why it is correct
A cheapest valid prefix ending in vendor v on day d must extend a valid prefix ending in some p != v on day d-1, and swapping in a cheaper prefix for the same p never breaks validity. So the recurrence captures the optimum. The best/second-best shortcut returns exactly the minimum over p != v of the previous row.
Complexity
- Time:
O(n * k). - Space:
O(n * k)for the predecessor pointers (the cost row itself needs onlyO(k)).
Reference solution
from array import array
from typing import List, Tuple
def cheapest_vendor_rotation(prices: List[List[int]]) -> Tuple[int, List[int]]:
if not prices:
return 0, []
n = len(prices)
k = len(prices[0])
if k == 1:
return sum(row[0] for row in prices), [0] * n
dp = prices[0][:]
parent = array('B', [0]) * (n * k)
for day in range(1, n):
first_value = float('inf')
first_vendor = -1
second_value = float('inf')
second_vendor = -1
for vendor, value in enumerate(dp):
if (value, vendor) < (first_value, first_vendor):
second_value, second_vendor = first_value, first_vendor
first_value, first_vendor = value, vendor
elif (value, vendor) < (second_value, second_vendor):
second_value, second_vendor = value, vendor
row = prices[day]
next_dp = [0] * k
offset = day * k
for vendor in range(k):
if vendor != first_vendor:
prev_value = first_value
prev_vendor = first_vendor
else:
prev_value = second_value
prev_vendor = second_vendor
next_dp[vendor] = row[vendor] + prev_value
parent[offset + vendor] = prev_vendor
dp = next_dp
final_vendor = min(range(k), key=lambda v: (dp[v], v))
total = dp[final_vendor]
plan = [0] * n
plan[-1] = final_vendor
for day in range(n - 1, 0, -1):
plan[day - 1] = parent[day * k + plan[day]]
return total, plan