{"id":"minimum-cost-for-tickets","title":"Minimum Cost For Tickets","difficulty":"medium","patterns":["dp-knapsack"],"primaryConcept":"dp-knapsack-optimization","concepts":["dp-knapsack-optimization"],"problemForm":"application","companies":["Google","Amazon","Meta","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"days","sizeMetric":"length","constraints":["positive","distinct","sorted"],"sizes":[8,16,32,64],"valueRange":{"min":1,"max":365},"secondaryParams":{"costs":{"strategy":"fixed","value":[2,7,15]}}},"description":"You are given an increasing list `days` where each value is a day you will travel, and `costs` where `costs[0]`, `costs[1]`, and `costs[2]` are the prices of 1-day, 7-day, and 30-day passes.\n\nReturn the minimum total cost needed to cover every travel day.","examples":[{"input":"days = [1,4,6,7,8,20], costs = [2,7,15]","output":"11","explanation":"Buy 1-day passes for days 1 and 20, and a 7-day pass covering days 4, 6, 7, and 8."},{"input":"days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]","output":"17","explanation":"A 30-day pass covers days 1 through 30, then a 1-day pass covers day 31."}],"constraints":[{"id":"1-len-days-365","text":"1 <= len(days) <= 365","check":{"kind":"sizeRange","target":"days","measure":"arrayLength","min":1,"max":365}},{"id":"1-days-i-365","text":"1 <= days[i] <= 365","check":{"kind":"valueRange","target":"days","selector":"arrayItems","min":1,"max":365}},{"id":"days-is-strictly-increasing","text":"days is strictly increasing","check":{"kind":"ordering","target":"days","order":"ascending","selector":"items"}},{"id":"len-costs-3","text":"len(costs) == 3","check":{"kind":"sizeRange","target":"costs","measure":"arrayLength","min":3,"max":3}},{"id":"1-costs-i-1000","text":"1 <= costs[i] <= 1000","check":{"kind":"valueRange","target":"costs","selector":"arrayItems","min":1,"max":1000}}],"starterCode":"class Solution:\n    def mincostTickets(self, days: list[int], costs: list[int]) -> int:\n        # Your code here\n        pass","functionName":"mincostTickets","testCases":[{"id":"1","input":{"days":[1,4,6,7,8,20],"costs":[2,7,15]},"expected":11,"description":"Classic mixed pass example."},{"id":"2","input":{"days":[1,2,3,4,5,6,7,8,9,10,30,31],"costs":[2,7,15]},"expected":17,"description":"A 30-day pass almost covers the full schedule."},{"id":"3","input":{"days":[1],"costs":[2,7,15]},"expected":2,"description":"Single travel day."},{"id":"4","input":{"days":[1,2,4,5,7,29,30],"costs":[3,8,20]},"expected":14,"description":"Two clusters are cheaper with separate short passes."},{"id":"5","input":{"days":[1,8,15,22,29],"costs":[5,6,20]},"expected":20,"description":"Sparse weekly travel favors several 7-day passes."},{"id":"h1","input":{"days":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],"costs":[4,10,25]},"expected":25,"description":"Dense month is best covered by one 30-day pass."},{"id":"h2","input":{"days":[5,6,7,8,40,41,42],"costs":[6,9,50]},"expected":18,"description":"Two separate weekly clusters."},{"id":"h3","input":{"days":[365],"costs":[9,20,50]},"expected":9,"description":"Last-day-only travel."},{"id":"h4","input":{"days":[1,7,8,9,15,16,17,365],"costs":[3,10,100]},"expected":24,"description":"Separated clusters plus a far single day should not force a 30-day pass."},{"id":"h5","input":{"days":[1,2,3,4,5,6,7,31,32,33,34,60],"costs":[2,9,20]},"expected":19,"description":"A weekly pass, a short cluster, and a final singleton combine independently."},{"id":"topup-year-spread","input":{"days":[1,30,60,120,200,365],"costs":[3,14,50]},"expected":18,"description":"Sparse travel across the year favors individual passes."},{"id":"topup-dense-month","input":{"days":[1,2,3,4,5,6,7,8,20,21,22],"costs":[2,7,20]},"expected":15,"description":"Dense travel clusters favor weekly coverage."}],"hints":[{"level":1,"content":"Think of `dp[day]` as the cheapest cost to cover all travel up to that calendar day."},{"level":2,"content":"If a day is not a travel day, its cost is the same as the previous day."},{"level":3,"content":"For a travel day, try ending with a 1-day, 7-day, or 30-day pass and take the minimum."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"try-all-subsets","name":"Try all pass combinations","summary":"Recursively decide which pass to buy at each travel day.","decisionReason":"At each travel day, choosing a 1-day, 7-day, or 30-day pass branches into three futures, and many futures land on the same next uncovered day. The recursion re-solves those suffixes unless the calendar cost is cached.","complexity":{"time":"O(3^n)","space":"O(n)"},"tradeoffs":["Runs in O(3^n) time and uses O(n) space."],"isOptimal":false},{"id":"calendar-dp","name":"Calendar day DP","summary":"Scan days from 1 to the last travel day and keep the cheapest covered cost for each day.","decisionReason":"dp[day] holds the cheapest cost to cover travel through that calendar day. Non-travel days copy the prior cost, and travel days take the cheapest of adding a 1-day, 7-day, or 30-day pass.","complexity":{"time":"O(lastDay)","space":"O(lastDay)"},"tradeoffs":["Runs in O(lastDay) time and uses O(lastDay) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-dp","title":"Initialize DP table","description":"Create a table for every day through the last travel day.","commonMistakes":["Allocating only one slot per travel day","Forgetting an unreachable sentinel value"],"hint":"Initialize all days to infinity before setting the zero-day base case.","semanticSpec":{"intent":"Allocate indexed state for minimum costs over calendar days.","doneWhen":"The DP table covers every day from 0 through the last travel day and starts with a high sentinel value.","shouldFailWhen":"This step should fail if no indexed cost state is allocated.","roles":["last day","cost table"],"mustProve":["An indexed state store is initialized with a sentinel value."],"mustNotAccept":["A scalar-only greedy accumulator."],"equivalentVariants":["Use an array or list indexed by calendar day."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_sentinel_indexed_state_store","scope":"init-dp","readMode":"dp-value-query-v1"}]}},{"id":"set-base-case","title":"Set zero-day base case","description":"Mark the cost before any travel days as zero.","commonMistakes":["Leaving `dp[0]` at infinity","Starting the first travel day with a pass cost before the table exists"],"hint":"Before buying any passes, covering zero days costs zero.","semanticSpec":{"intent":"Seed the indexed cost table with a zero base case.","doneWhen":"`dp[0]` or an equivalent zero-day cell is assigned zero.","shouldFailWhen":"This step should fail if the DP never writes a zero base case.","roles":["zero day","cost table"],"mustProve":["The zero index base case is written."],"mustNotAccept":["Starting every state at a pass cost."],"equivalentVariants":["Use a sentinel day before the first travel day."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_zero_index_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]}},{"id":"scan-days","title":"Scan calendar days","description":"Visit each calendar day up to the last travel day.","commonMistakes":["Skipping non-travel days without carrying cost forward","Stopping before the last travel day"],"hint":"The calendar scan lets pass durations jump back to earlier day states.","semanticSpec":{"intent":"Traverse the indexed DP state space.","doneWhen":"The implementation loops through day indices that correspond to DP cells.","shouldFailWhen":"This step should fail if there is no indexed state-space scan.","roles":["day index","DP table"],"mustProve":["The indexed state space is scanned."],"mustNotAccept":["Trying pass combinations without a DP table."],"equivalentVariants":["Scan all calendar days or scan travel days with equivalent indexed state."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]}},{"id":"try-passes","title":"Try pass choices","description":"For each travel day, consider all three pass durations.","commonMistakes":["Always buying a 1-day pass","Considering only weekly and monthly passes"],"hint":"The inner loop should compare 1-day, 7-day, and 30-day transitions.","semanticSpec":{"intent":"Enumerate the fixed pass choices for each DP state.","doneWhen":"The code has a nested choice scan inside the day-state scan.","shouldFailWhen":"This step should fail if only one pass length is considered.","roles":["pass duration","pass cost"],"mustProve":["A nested choice state space is scanned."],"mustNotAccept":["A single hard-coded pass length."],"equivalentVariants":["Loop over indexes, tuples, or parallel duration and cost arrays."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]}},{"id":"update-dp","title":"Write minimum-cost transition","description":"Use each pass to transition from the previous uncovered day and keep the cheapest cost.","commonMistakes":["Reading a negative previous-day index when the pass reaches before day 0","Adding a pass cost without taking the minimum"],"hint":"If the pass reaches before day 0, compare against `dp[0] + cost`.","semanticSpec":{"intent":"Update the current day with the cheapest valid previous state plus pass cost.","doneWhen":"The DP cell is guarded by pass fit and written with a min-cost transition.","shouldFailWhen":"This step should fail if the transition is unguarded or not minimizing.","roles":["current day","previous day","pass cost"],"mustProve":["The indexed transition is guarded by input fit and writes a minimum cost."],"mustNotAccept":["An additive count transition or greedy overwrite."],"equivalentVariants":["Use an explicit `if day >= duration` branch or an equivalent clamped previous index."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"guards_and_writes_min_cost_indexed_transition","scope":"update-dp","readMode":"dp-value-query-v1"}]}},{"id":"return-result","title":"Return final cost","description":"Return the DP value for the last travel day.","commonMistakes":["Returning the last pass cost","Returning the whole DP table"],"hint":"The answer is the terminal indexed state.","semanticSpec":{"intent":"Return the terminal DP state for the schedule.","doneWhen":"The function returns the cost table entry at the last travel day.","shouldFailWhen":"This step should fail if the final indexed state is not returned.","roles":["last day","cost table"],"mustProve":["The terminal indexed state is returned."],"mustNotAccept":["Returning an intermediate day or a scalar choice."],"equivalentVariants":["Return `dp[last_day]` or the equivalent final covered day cell."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]}}],"slides":[{"id":"opener","chapter":"The schedule","kind":"info","eyebrow":"Read the problem","title":"Cover every travel day for the least money","workspacePanel":"problem","body":["You travel on the days in `days`, and you can buy a 1-day, 7-day, or 30-day pass at the three prices in `costs`. A pass bought on a day covers that day and the next few calendar days. Return the cheapest total that covers every travel day.","Grabbing the biggest pass whenever you travel is not always right, and neither is always buying singles. The safe move is to try every pass at every travel day. Watch what that costs."]},{"id":"brute-force","chapter":"The obvious way","kind":"code-trace","eyebrow":"The obvious way","title":"Try every pass at every travel day","summary":"Trying every pass at every travel day finds the cheapest plan, but the same remaining schedule keeps getting re-solved. Watch how fast that re-solving piles up.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def mincostTickets(days: list[int], costs: list[int]) -> int:\n    passes: list[list[int]] = [[1, costs[0]], [7, costs[1]], [30, costs[2]]]\n    INF = 1000000\n    def cheapest(i: int) -> int:\n        if i == len(days):\n            return 0\n        best = INF\n        for duration, cost in passes:\n            j = i\n            while j < len(days) and days[j] < days[i] + duration:\n                j += 1\n            best = min(best, cost + cheapest(j))\n        return best\n    return cheapest(0)","steps":[{"id":"fork-at-day1","title":"Day 1 forks by pass","codeLine":8,"summary":"From the travel day 1, a 1-day pass jumps to the next uncovered travel day, a 7-day pass jumps past day 7, and a 30-day pass jumps past day 30. Each choice spawns a smaller schedule to solve.","state":{"nums":[1,4,6,7,8,20],"i":0,"labels":{"nums":"days","i":"i"}}},{"id":"reaches-day20","title":"Several plans land on day 20","codeLine":11,"summary":"A 7-day pass from day 1 lands on day 8, then leaves day 20. Buying singles for days 1, 4, 6, 7, 8 also leaves day 20. The same remaining day gets solved on more than one path.","state":{"nums":[1,4,6,7,8,20],"i":5,"labels":{"nums":"days","i":"i"}}},{"id":"resolve-suffix","title":"The same suffix, solved again and again","codeLine":6,"summary":"Covering the days from day 20 onward is the same subproblem no matter how you reached it, yet every branch re-solves it from scratch. The work multiplies as the schedule grows.","state":{"nums":[1,4,6,7,8,20],"i":5,"labels":{"nums":"days","i":"i"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const passes = [[1, costs[0]], [7, costs[1]], [30, costs[2]]];\nconst INF = 1000000;\nfunction cheapest(i) {\n    if (i == days.length) {\n        return 0;\n    }\n    let best = INF;\n    for (const [duration, cost] of passes) {\n        let j = i;\n        while ((j < days.length) && (days[j] < (days[i] + duration))) {\n            j++;\n        }\n        best = Math.min(best, (cost + cheapest(j)));\n    }\n    return best;\n}\nreturn cheapest(0);","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":13,"13":15,"14":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"11":{"startLine":11,"endLine":12},"12":{"startLine":13,"endLine":14},"13":{"startLine":15,"endLine":16}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const passes = [[1, costs[0]], [7, costs[1]], [30, costs[2]]];\nconst INF = 1000000;\nfunction cheapest(i: number): number {\n    if (i == days.length) {\n        return 0;\n    }\n    let best = INF;\n    for (const [duration, cost] of passes) {\n        let j = i;\n        while ((j < days.length) && (days[j] < (days[i] + duration))) {\n            j++;\n        }\n        best = Math.min(best, (cost + cheapest(j)));\n    }\n    return best;\n}\nreturn cheapest(0);","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"8":8,"9":9,"10":10,"11":11,"12":13,"13":15,"14":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"11":{"startLine":11,"endLine":12},"12":{"startLine":13,"endLine":14},"13":{"startLine":15,"endLine":16}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<int>> passes = new() { new List<int> { 1, costs[0] }, new List<int> { 7, costs[1] }, new List<int> { 30, costs[2] } };\nint INF = 1000000;\nint Cheapest(int i) {\n    if (i == days.Count) {\n        return 0;\n    }\n    int best = INF;\n    foreach (var item in passes) {\n        int duration = item[0];\n        int cost = item[1];\n        int j = i;\n        while (j < days.Count && days[j] < days[i] + duration) {\n            j++;\n        }\n        best = Math.Min(best, cost + Cheapest(j));\n    }\n    return best;\n    return 0;\n}\nreturn Cheapest(0);","lineMap":{"2":1,"3":2,"5":4,"6":5,"7":7,"8":8,"9":11,"10":12,"11":13,"12":15,"13":17,"14":20},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":5,"endLine":6},"8":{"startLine":8,"endLine":10},"11":{"startLine":13,"endLine":14},"12":{"startLine":15,"endLine":16},"13":{"startLine":17,"endLine":19}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int)> cheapest;\n\nvector<vector<int>> passes{{1, costs[0]}, {7, costs[1]}, {30, costs[2]}};\nint INF = 1000000;\ncheapest = [&]( int i ) -> int {\n    if (i == days.size()) {\n        return 0;\n    }\n    int best = INF;\n    for (vector<int> item : passes) {\n        int duration = item[0];\n        int cost = item[1];\n        int j = i;\n        while ((j < days.size() && days[j] < (days[i] + duration))) {\n            j++;\n        }\n        best = min(best, (cost + cheapest(j)));\n    }\n    return best;\n};\nreturn cheapest(0);","lineMap":{"2":3,"3":4,"5":6,"6":7,"7":9,"8":10,"9":13,"10":14,"11":15,"12":17,"13":19,"14":21},"statementBundles":{"3":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":8},"8":{"startLine":10,"endLine":12},"11":{"startLine":15,"endLine":16},"12":{"startLine":17,"endLine":18},"13":{"startLine":19,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int cheapest(int i, List<Integer> days, int INF, List<List<Integer>> passes) {\n    if (i == days.size()) {\n        return 0;\n    }\n    int best = INF;\n    for (List<Integer> pass : passes) {\n        int duration = pass.get(0);\n        int cost = pass.get(1);\n        int j = i;\n        while ((j < days.size() && days.get(j) < (days.get(i) + duration))) {\n            j++;\n        }\n        best = Math.min(best, (cost + cheapest(j, days, INF, passes)));\n    }\n    return best;\n}\n\nList<List<Integer>> passes = new ArrayList<>(Arrays.asList(new ArrayList<>(List.of(1, costs.get(0))), new ArrayList<>(List.of(7, costs.get(1))), new ArrayList<>(List.of(30, costs.get(2)))));\nint INF = 1000000;\nreturn cheapest(0, days, INF, passes);","lineMap":{"2":18,"3":19,"5":2,"6":3,"7":5,"8":6,"9":9,"10":10,"11":11,"12":13,"13":15,"14":20},"statementBundles":{"6":{"startLine":3,"endLine":4},"8":{"startLine":6,"endLine":8},"11":{"startLine":11,"endLine":12},"12":{"startLine":13,"endLine":14},"13":{"startLine":15,"endLine":16}}}}},"body":["At each travel day, try every pass, skip ahead to the first day the pass no longer covers, and recurse on the rest."]},{"id":"cost-beat","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the cost","title":"What happens to the work as the schedule grows?","summary":"The same remaining travel day appears under more than one branch.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cost-beat-branch","state":{"nums":[1,4,6,7,8,20],"i":4,"labels":{"nums":"days","i":"i"}}}]},"options":[{"id":"explodes","label":"It explodes: each travel day branches into several smaller schedules that branch again","rationale":"From one travel day you recurse on the days each pass leaves uncovered, and every branch does the same. The number of calls grows like a tree, so a schedule of a few dozen days can mean an enormous number of recursive calls.","isCorrect":true},{"id":"linear","label":"It grows in step with the schedule, one call per travel day","rationale":"If each suffix were solved once this would hold, but nothing stops the same suffix from being re-entered down many different branches, so the calls multiply instead of counting once.","isCorrect":false},{"id":"passes-only","label":"It grows only with the three pass lengths","rationale":"Three passes widen each fork to three branches, and the depth still grows with the number of travel days. The schedule length drives the call tree.","isCorrect":false}],"answer":"It explodes. Each travel day forks into the suffixes left by each pass, and those fork again, so the call tree grows roughly exponentially as the schedule grows."},{"id":"repeated-work","chapter":"The obvious way","kind":"case-probe","eyebrow":"Name the waste","title":"What is identical across every branch that reaches the same remaining day?","summary":"Day 20 is reached by a 7-day pass from day 1, and also by buying singles up to day 8.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-work-suffix","state":{"nums":[1,4,6,7,8,20],"i":5,"labels":{"nums":"days","i":"i"}}}]},"options":[{"id":"cheapest-suffix","label":"The cheapest cost to cover the travel days from that day onward, identical no matter which path arrived","rationale":"Once a branch is standing on day 20 with the same days left to cover, the cheapest way to finish is the same subproblem regardless of how it got there. That reusable answer is the cheapest cost to cover the remaining suffix, so each distinct remaining day has one answer worth memoizing.","isCorrect":true},{"id":"pass-list","label":"Reading the three pass prices","rationale":"Scanning the three passes is cheap, and it is the same scan everywhere, but it is not the expensive thing being repeated. The whole remaining schedule is re-solved each time.","isCorrect":false},{"id":"the-min","label":"Comparing costs with min","rationale":"The min is one cheap comparison. What repeats underneath it is the entire recomputation of a suffix whose cheapest cover is already fixed.","isCorrect":false}],"answer":"The cheapest cost to cover the days from that day onward is the same on every path that reaches it. One answer per remaining day is all that has to be memoized."},{"id":"from-suffix-to-table","chapter":"The idea","kind":"info","eyebrow":"Turn waste into state","title":"From re-solved suffixes to one cost per day","workspacePanel":"visualizer","body":["Memoizing the cheapest cover for each remaining day removes the repeated work: each distinct day is solved once. That recursive table is indexed by day, which is exactly the state we will keep.","It is easier to fill that table forward than to recurse. Instead of asking the cost to cover from a day onward, we read it the other way: `dp[day]` is the cheapest cost to cover every travel day up to that calendar day. Both store one answer per day; filling forward just lets each day read an already-solved earlier day.","So size a table over the calendar days, seed day 0 at cost 0, and fill upward. Each travel day will compare the pass choices against already-solved earlier days."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"from-suffix-state","state":{"dp":[0,null,null,null,null,null,null,null,null],"current":0,"labels":{"dp":"dp","current":"day"}}}]}},{"id":"the-rule","chapter":"The idea","kind":"case-probe","eyebrow":"Build the rule","title":"On a travel day, the cheapest cover is built from which earlier days?","summary":"costs = [2, 7, 15] for 1-day, 7-day, and 30-day passes; the table is solved up to day 7 and you reach travel day 8.","workspacePanel":"visualizer","options":[{"id":"pass-jumpback","label":"The cheapest of: each pass price plus the cost already known one pass-length earlier","rationale":"A pass bought to cover day 8 also covers the days just before it, so its cost is its price plus the cheapest cover for the day it reaches back to. The 1-day pass adds 2 to the cost at day 7; the 7-day pass adds 7 to the cost at day 1. Take the smallest over the three passes.","isCorrect":true},{"id":"just-prev","label":"One pass price plus the cost for the day before","rationale":"That only ever uses a 1-day pass. A 7-day or 30-day pass reaches much further back and is often cheaper per day covered, so every pass length must be tried.","isCorrect":false},{"id":"sum-passes","label":"The costs for all three passes added together","rationale":"You buy one pass to land on this day, not all three at once. The rule takes the minimum over the passes, not their sum.","isCorrect":false}],"answer":"The cheapest of each pass: its price plus the cost already known at the day it reaches back to. For day 8 a 1-day pass gives costs[0] + dp[7] and a 7-day pass gives costs[1] + dp[1]. Non-travel days simply copy the cost from the day before.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rule-state","state":{"dp":[0,2,2,2,4,4,6,7,null],"current":8,"labels":{"dp":"dp","current":"day"}}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the table","title":"Trace the table filling","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"day-2-carry","state":{"dp":[0,2,2,null,null,null,null,null,null],"current":2,"labels":{"dp":"dp","current":"day"}}},{"id":"day-8-choose","state":{"dp":[0,2,2,2,4,4,6,7,9],"current":8,"labels":{"dp":"dp","current":"day"}}},{"id":"day-20-final","state":{"dp":[0,2,2,2,4,4,6,7,9,9,9,9,9,9,9,9,9,9,9,9,11],"current":20,"labels":{"dp":"dp","current":"day"}}}]},"beats":[{"id":"day-2-carry","title":"Day 2 is not a travel day. What does it cost?","summary":"Day 1 is solved at 2, and day 2 is not in the travel list.","prompt":"The table reaches day 2.","options":[{"id":"carry","label":"2, the same as day 1","rationale":"No travel happens on day 2, so no new pass is needed. The cheapest cover is whatever already covered day 1, copied forward.","isCorrect":true},{"id":"buy","label":"4, a fresh 1-day pass on top of day 1","rationale":"Buying a pass for a day you do not travel wastes money. A non-travel day copies the previous cost unchanged.","isCorrect":false},{"id":"zero","label":"0, nothing is owed yet","rationale":"Day 1 already required a pass costing 2, and that obligation carries forward. Day 2 inherits 2, not 0.","isCorrect":false}],"answer":"2. Day 2 has no travel, so it copies day 1's cost of 2 forward."},{"id":"day-8-choose","title":"Day 8 with passes [2, 7, 15]. What does the table get?","summary":"Days up to 7 are solved at costs 2, 2, 2, 4, 4, 6, 7, and day 1 is solved at 2.","prompt":"The table reaches travel day 8.","options":[{"id":"nine","label":"9","rationale":"A 1-day pass gives dp[7] + 2 = 7 + 2 = 9, and a 7-day pass reaching back to day 1 gives dp[1] + 7 = 2 + 7 = 9. Both land on 9, the cheapest cover for day 8.","isCorrect":true},{"id":"four","label":"4","rationale":"That would be dp[7] alone without paying for day 8's pass. Day 8 is a travel day, so it must add a pass on top of an earlier cost; the cheapest reaches 9.","isCorrect":false},{"id":"fifteen","label":"15","rationale":"A 30-day pass at 15 does cover day 8, but a 1-day or 7-day pass covers it for 9. The table keeps the smaller plan.","isCorrect":false}],"answer":"9. A 1-day pass gives dp[7] + 2 = 9 and a 7-day pass gives dp[1] + 7 = 9, so dp[8] = 9."},{"id":"day-20-final","title":"Day 20: which pass gives the cheapest cover?","summary":"dp holds 9 for every day from 8 through 19, and day 20 is the last travel day.","prompt":"The table reaches the last travel day, day 20.","options":[{"id":"eleven","label":"11, a 1-day pass on top of day 19","rationale":"A 1-day pass reaches back to day 19, whose cost is 9, so dp[20] = costs[0] + dp[19] = 2 + 9 = 11. A 7-day pass reaches day 13 (also 9) for 16, and a 30-day pass costs 15, so the single is cheapest.","isCorrect":true},{"id":"sixteen","label":"16, a second 7-day pass","rationale":"A 7-day pass reaches back to day 13, costing 9 + 7 = 16. Day 20 travels alone after the first cluster, so a 1-day pass covers it for less.","isCorrect":false},{"id":"fifteen","label":"15, a 30-day pass","rationale":"A 30-day pass reaches before day 0 for 15 total, but adding one 1-day pass to the already-cheap day-19 cost totals only 11.","isCorrect":false}],"answer":"11. A 1-day pass reaches back to day 19 (cost 9), so dp[20] = 2 + 9 = 11, the final answer."}]},{"id":"carry-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could the table skip the days with no travel?","summary":"Writing a cost only on travel days looks tidy, and it does fill every travel day. Watch a later pass try to reach back to a day that was skipped.","workspacePanel":"trace","pitfall":"The table below writes a cost only on travel days and leaves the gaps between them empty.","whyItMatters":"A pass that reaches back to a non-travel day reads an empty cell, so its candidate cost is treated as unreachable and the table misses the cheap plan. Carry the previous day's cost across every non-travel day, so every cell a pass can reach back to already holds the cheapest cover.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def mincostTickets(days: list[int], costs: list[int]) -> int:\n    durations = [1, 7, 30]\n    last_day = days[-1]\n    dp = [1000000] * (last_day + 1)\n    dp[0] = 0\n    for day in days:\n        for i in range(3):\n            if day >= durations[i]:\n                dp[day] = min(dp[day], dp[day - durations[i]] + costs[i])\n            else:\n                dp[day] = min(dp[day], dp[0] + costs[i])\n    return dp[last_day]","steps":[{"id":"skip-gaps","title":"Only travel days are filled","codeLine":6,"summary":"days = [1, 8], costs = [2, 7, 15]. Day 1 gets cost 2, but days 2 through 7 are never written and stay unreachable.","state":{"dp":[0,2,"INF","INF","INF","INF","INF","INF","INF"],"current":1,"labels":{"dp":"dp","current":"day"}}},{"id":"read-empty","title":"Day 8's 1-day pass reaches an empty cell","codeLine":9,"summary":"At day 8 a 1-day pass reaches back to day 7, but dp[7] was never filled. The candidate becomes unreachable plus 2, so this cheap option is thrown away.","state":{"dp":[0,2,"INF","INF","INF","INF","INF","INF","INF"],"current":8,"labels":{"dp":"dp","current":"day"}}},{"id":"overpays","title":"It overpays for day 8","codeLine":9,"summary":"With day 7 unreachable, the only working option is the 7-day pass from day 1, giving dp[8] = 9 instead of the correct 4. The skipped gaps broke the cheap 1-day plan.","state":{"dp":[0,2,"INF","INF","INF","INF","INF","INF",9],"current":8,"labels":{"dp":"dp","current":"day"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const durations = [1, 7, 30];\nconst lastDay = days[(days.length - 1)];\nconst dp = Array((lastDay + 1)).fill(1000000);\ndp[0] = 0;\nfor (const day of days) {\n    for (let i = 0; i < 3; i++) {\n        if (day >= durations[i]) {\n            dp[day] = Math.min(dp[day], (dp[(day - durations[i])] + costs[i]));\n        } else {\n            dp[day] = Math.min(dp[day], (dp[0] + costs[i]));\n        }\n    }\n}\nreturn dp[lastDay];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const durations = [1, 7, 30];\nconst lastDay = days[(days.length - 1)];\nconst dp = Array((lastDay + 1)).fill(1000000);\ndp[0] = 0;\nfor (const day of days) {\n    for (let i = 0; i < 3; i++) {\n        if (day >= durations[i]) {\n            dp[day] = Math.min(dp[day], (dp[(day - durations[i])] + costs[i]));\n        } else {\n            dp[day] = Math.min(dp[day], (dp[0] + costs[i]));\n        }\n    }\n}\nreturn dp[lastDay];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> durations = new ArrayList<>(List.of(1, 7, 30));\nint lastDay = days.get((days.size() - 1));\nList<Integer> dp = new ArrayList<>();\nfor (int index = 0; index < (lastDay + 1); index++) {\n    dp.add(1000000);\n}\ndp.set(0, 0);\nfor (Integer day : days) {\n    for (int i = 0; i < 3; i++) {\n        if (day >= durations.get(i)) {\n            dp.set(day, Math.min(dp.get(day), (dp.get((day - durations.get(i))) + costs.get(i))));\n        } else {\n            dp.set(day, Math.min(dp.get(day), (dp.get(0) + costs.get(i))));\n        }\n    }\n}\nreturn dp.get(lastDay);","lineMap":{"2":1,"3":2,"4":3,"5":7,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":17},"statementBundles":{"4":{"startLine":3,"endLine":6},"11":{"startLine":13,"endLine":16}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> durations = new() { 1, 7, 30 };\nint lastDay = days[days.Count - 1];\nList<int> dp = Enumerable.Repeat<int>(1000000, lastDay + 1).ToList();\ndp[0] = 0;\nforeach (int day in days) {\n    for (int i = 0; i < 3; i++) {\n        if (day >= durations[i]) {\n            dp[day] = Math.Min(dp[day], dp[day - durations[i]] + costs[i]);\n        } else {\n            dp[day] = Math.Min(dp[day], dp[0] + costs[i]);\n        }\n    }\n}\nreturn dp[lastDay];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> durations{1, 7, 30};\nint last_day = days[(days.size() - 1)];\nvector<int> dp = vector<int>((last_day + 1), 1000000);\ndp[0] = 0;\nfor (int day : days) {\n    for (int i = 0; i < 3; i++) {\n        if (day >= durations[i]) {\n            dp[day] = min(dp[day], (dp[(day - durations[i])] + costs[i]));\n        } else {\n            dp[day] = min(dp[day], (dp[0] + costs[i]));\n        }\n    }\n}\nreturn dp[last_day];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Carrying the cost across non-travel days and taking the cheapest pass at each travel day fills the table from day 0 upward.","Two inputs sit at the boundary of that rule: an early travel day where a pass reaches back before the calendar starts, and a schedule with a single travel day."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"dp":[0,null,null,null,null,null,null,null,null],"current":1,"labels":{"dp":"dp","current":"day"}}}]}},{"id":"early-pass-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does a 7-day pass cost on an early travel day?","summary":"days = [3], costs = [2, 7, 15], buying a 7-day pass for day 3.","workspacePanel":"visualizer","options":[{"id":"clamp-zero","label":"7, the price plus the cost at day 0","rationale":"A 7-day pass on day 3 reaches back past day 0. Covering nothing before the first day costs 0, so the candidate is 7 + dp[0] = 7. The reach-back is clamped to day 0 rather than indexing before the table.","isCorrect":true},{"id":"negative","label":"Whatever sits at index day minus 7","rationale":"Day 3 minus 7 is below day 0, off the front of the table. Reading there is a bug. Clamp the reach-back to day 0, whose cost is the base 0.","isCorrect":false},{"id":"skip","label":"The pass cannot be used this early","rationale":"A pass that overshoots the start is perfectly usable. It just covers some days before the trip began, which is free, so its candidate cost is the price plus dp[0].","isCorrect":false}],"answer":"7. The reach-back clamps to day 0, where the cost is 0, so the 7-day pass candidate is costs[1] + dp[0] = 7.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"early-pass-state","state":{"dp":[0,0,0,null],"current":3,"labels":{"dp":"dp","current":"day"}}}]}},{"id":"single-day-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What is the cheapest cover for a single travel day?","summary":"days = [1], costs = [2, 7, 15].","workspacePanel":"visualizer","options":[{"id":"cheapest-pass","label":"2, the cheapest pass that covers it","rationale":"One travel day needs exactly one pass. All three passes cover day 1, each reaching back to day 0 at cost 0, so the answer is the smallest price, the 1-day pass at 2.","isCorrect":true},{"id":"all-three","label":"24, all three passes bought","rationale":"You only need one pass to cover a single day. The rule takes the minimum over the passes, not their sum.","isCorrect":false},{"id":"zero","label":"0, the table starts at day 0","rationale":"Day 0 is the empty base at cost 0, but day 1 is a real travel day that needs covering. Its cheapest pass costs 2.","isCorrect":false}],"answer":"2. A single travel day takes the cheapest single pass, dp[1] = costs[0] + dp[0] = 2.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-day-state","state":{"dp":[0,2],"current":1,"labels":{"dp":"dp","current":"day"}}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Every cell a pass can reach back to must already hold the cheapest cover, so fill day 0 first and carry costs across the gaps.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"dp":[0,null,null,null,null,null,null,null,null],"current":1,"labels":{"dp":"dp","current":"day"}}}]},"body":["Size a table to the last travel day, seed day 0 at cost 0, and fill upward. On a non-travel day, copy the previous day's cost. On a travel day, try each pass, reach back to the day it leaves uncovered, and keep the cheapest price plus that earlier cost. The answer is the cell for the last travel day."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Code the calendar-day table","eyebrow":"Code the rule","summary":"Now build the table that earns the cheapest cover: size it over the calendar and seed day 0 at cost 0, scan each day, and on a travel day try all three passes, take the cheapest price plus the cost at the day it reaches back to (clamped to day 0), then return the last day's cell.","workspacePanel":"code","checkpoints":[{"id":"init-dp","title":"Initialize DP table","description":"Create a table for every day through the last travel day.","commonMistakes":["Allocating only one slot per travel day","Forgetting an unreachable sentinel value"],"hint":"Initialize all days to infinity before setting the zero-day base case.","semanticSpec":{"intent":"Allocate indexed state for minimum costs over calendar days.","doneWhen":"The DP table covers every day from 0 through the last travel day and starts with a high sentinel value.","shouldFailWhen":"This step should fail if no indexed cost state is allocated.","roles":["last day","cost table"],"mustProve":["An indexed state store is initialized with a sentinel value."],"mustNotAccept":["A scalar-only greedy accumulator."],"equivalentVariants":["Use an array or list indexed by calendar day."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_sentinel_indexed_state_store","scope":"init-dp","readMode":"dp-value-query-v1"}]}},{"id":"set-base-case","title":"Set zero-day base case","description":"Mark the cost before any travel days as zero.","commonMistakes":["Leaving the day-zero cell at infinity","Starting the first travel day with a pass cost before the table exists"],"hint":"Before buying any passes, covering zero days costs zero.","semanticSpec":{"intent":"Seed the indexed cost table with a zero base case.","doneWhen":"The day-zero cell is assigned zero.","shouldFailWhen":"This step should fail if the DP never writes a zero base case.","roles":["zero day","cost table"],"mustProve":["The zero index base case is written."],"mustNotAccept":["Starting every state at a pass cost."],"equivalentVariants":["Use a sentinel day before the first travel day."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_zero_index_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]}},{"id":"scan-days","title":"Scan calendar days","description":"Visit each calendar day up to the last travel day.","commonMistakes":["Skipping non-travel days without carrying cost forward","Stopping before the last travel day"],"hint":"The calendar scan lets pass durations jump back to earlier day states.","semanticSpec":{"intent":"Traverse the indexed DP state space.","doneWhen":"The implementation loops through day indices that correspond to DP cells.","shouldFailWhen":"This step should fail if there is no indexed state-space scan.","roles":["day index","DP table"],"mustProve":["The indexed state space is scanned."],"mustNotAccept":["Trying pass combinations without a DP table."],"equivalentVariants":["Scan all calendar days or scan travel days with equivalent indexed state."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]}},{"id":"try-passes","title":"Try pass choices","description":"For each travel day, consider all three pass durations.","commonMistakes":["Always buying a 1-day pass","Considering only weekly and monthly passes"],"hint":"The inner loop should compare 1-day, 7-day, and 30-day transitions.","semanticSpec":{"intent":"Enumerate the fixed pass choices for each DP state.","doneWhen":"The code has a nested choice scan inside the day-state scan.","shouldFailWhen":"This step should fail if only one pass length is considered.","roles":["pass duration","pass cost"],"mustProve":["A nested choice state space is scanned."],"mustNotAccept":["A single hard-coded pass length."],"equivalentVariants":["Loop over indexes, tuples, or parallel duration and cost arrays."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]}},{"id":"update-dp","title":"Write minimum-cost transition","description":"Use each pass to transition from the day it reaches back to and keep the cheapest cost.","commonMistakes":["Reaching back past day zero without clamping the index","Adding a pass cost without taking the minimum"],"hint":"If the pass reaches before day zero, compare against the day-zero cost plus the pass price.","semanticSpec":{"intent":"Update the current day with the cheapest valid previous state plus pass cost.","doneWhen":"The DP cell is guarded by pass fit and written with a min-cost transition.","shouldFailWhen":"This step should fail if the transition is unguarded or not minimizing.","roles":["current day","previous day","pass cost"],"mustProve":["The indexed transition is guarded by input fit and writes a minimum cost."],"mustNotAccept":["An additive count transition or greedy overwrite."],"equivalentVariants":["Use an explicit day-fits-duration branch or an equivalent clamped previous index."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"guards_and_writes_min_cost_indexed_transition","scope":"update-dp","readMode":"dp-value-query-v1"}]}},{"id":"return-result","title":"Return final cost","description":"Return the DP value for the last travel day.","commonMistakes":["Returning the last pass cost","Returning the whole DP table"],"hint":"The answer is the terminal indexed state.","semanticSpec":{"intent":"Return the terminal DP state for the schedule.","doneWhen":"The function returns the cost table entry at the last travel day.","shouldFailWhen":"This step should fail if the final indexed state is not returned.","roles":["last day","cost table"],"mustProve":["The terminal indexed state is returned."],"mustNotAccept":["Returning an intermediate day or a scalar choice."],"equivalentVariants":["Return the final covered day cell."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Wrap up","title":"You built the calendar-day table","summary":"One cost per day, the cheapest pass at each travel day.","workspacePanel":"code","takeaways":[{"title":"One cost per calendar day is enough state","body":"The cheapest cover for a day does not depend on how the schedule reached it."},{"title":"Each pass reaches back to an earlier day","body":"On a travel day, a pass costs its price plus the cheapest cover at the day it reaches back to. The reach-back clamps to day 0, so an early pass reads the free base instead of indexing off the table."},{"title":"Days without travel copy the previous cost","body":"Copying forward keeps every cell a pass might reach back to filled."},{"title":"The table takes O(lastDay) time and space","body":"Each day from 0 to the last travel day does at most three lookups, far below the O(3^n) of trying every pass at every travel day."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"starterFunctionName":"mincostTickets","tags":["Dynamic Programming","Knapsack","Timeline DP"]}
