Bird
Raised Fist0
Interview Prepdp-knapsackmediumAmazonGoogle

Minimum Cost for Tickets

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
</>
IDE
def mincostTickets(days: list[int], costs: list[int]) -> int:public int mincostTickets(int[] days, int[] costs)int mincostTickets(vector<int> days, vector<int> costs)function mincostTickets(days, costs)
def mincostTickets(days, costs):
    # Write your solution here
    pass
class Solution {
    public int mincostTickets(int[] days, int[] costs) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int mincostTickets(vector<int> days, vector<int> costs) {
    // Write your solution here
    return 0;
}
function mincostTickets(days, costs) {
    // Write your solution here
}
0/10
Common Bugs to Avoid
Wrong: 14Summing only 1-day passes without considering longer passes.At each day, compute min cost among 1-day, 7-day, and 30-day passes covering that day.
Wrong: 0Not handling empty input or base case properly.Return 0 if days array is empty.
Wrong: 9Off-by-one error in coverage calculation causing undercoverage.Ensure pass covers days[i] through days[i] + duration - 1 inclusive.
Wrong: Too slow / TLEBrute force recursion without memoization or optimization.Implement memoization or bottom-up DP with binary search optimization.
Wrong: Incorrect cost due to 0/1 knapsack assumptionRestricting pass purchase to once instead of unbounded times.Allow multiple purchases of same pass type in DP recurrence.
Test Cases
t1_01basic
Input{"days":[1,4,6,7,8,20],"costs":[2,7,15]}
Expected11

Buy 1-day pass on day 1 (cost 2), 7-day pass on day 4 (cost 7) covering days 4-10, and 1-day pass on day 20 (cost 2). Total = 11.

t1_02basic
Input{"days":[1,2,3,4,5,6,7],"costs":[2,7,15]}
Expected7

Buying a 7-day pass for 7 covers all days at cost 7, cheaper than multiple 1-day passes (2*7=14).

t2_01edge
Input{"days":[],"costs":[2,7,15]}
Expected0

No travel days means no cost.

t2_02edge
Input{"days":[1],"costs":[2,7,15]}
Expected2

Single travel day; cheapest is 1-day pass costing 2.

t2_03edge
Input{"days":[1,2,3,4,5,6,7],"costs":[2,7,15]}
Expected7

Exact boundary test where 7-day pass covers all days exactly at cost 7.

t2_04edge
Input{"days":[1,15,30],"costs":[2,7,15]}
Expected6

Three 1-day passes cheaper than longer passes; tests unbounded vs 0/1 confusion.

t3_01corner
Input{"days":[1,2,3,4,5,6,7,8,9,10],"costs":[10,2,1]}
Expected1

1-day passes are expensive, 7-day pass very cheap; best to buy one 7-day pass and three 1-day passes or one 30-day pass is too expensive.

t3_02corner
Input{"days":[1,15,30],"costs":[2,7,15]}
Expected6

Three 1-day passes cheaper than longer passes; tests unbounded vs 0/1 confusion.

t3_03corner
Input{"days":[1,3,5,7,9],"costs":[3,8,20]}
Expected11

Tests off-by-one errors in coverage calculation; buying 1-day passes on days 1,3,5,7,9 costs 15, cheaper than 7-day or 30-day passes.

t4_01performance
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,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100],"costs":[2,7,15]}
⏱ Performance - must finish in 2000ms

n=100, O(n^2) brute force will TLE; efficient DP with memoization or binary search optimization required.

Practice

(1/5)
1. You are given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity. You want to maximize the total value of items placed in the knapsack without exceeding its capacity. Which algorithmic approach guarantees finding the optimal solution for this problem?
easy
A. A greedy algorithm that picks items with the highest value-to-weight ratio first.
B. Dynamic programming that considers including or excluding each item for every capacity up to the maximum.
C. A simple recursive approach without memoization that tries all subsets of items.
D. A breadth-first search exploring all possible combinations of items.

Solution

  1. Step 1: Understand problem constraints and overlapping subproblems

    The problem requires maximizing value without exceeding capacity, which is a classic optimization problem with overlapping subproblems suitable for dynamic programming.
  2. Step 2: Identify algorithmic approach that guarantees optimality

    Greedy algorithms fail because picking locally optimal items (highest value/weight) does not guarantee global optimum. Exhaustive search is correct but inefficient. Dynamic programming systematically explores all item inclusion/exclusion states with memoization, ensuring optimality.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    DP solves 0/1 Knapsack optimally by exploring all states [OK]
Hint: DP with inclusion/exclusion ensures optimal solution [OK]
Common Mistakes:
  • Greedy approach works for fractional knapsack, not 0/1 knapsack.
2. You are given a list of jobs where each job has a start time, an end time, and a profit. You want to schedule jobs to maximize total profit such that no two jobs overlap. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Dynamic programming with jobs sorted by end time and binary search to find compatible jobs
B. Pure brute force recursion checking all subsets of jobs
C. Greedy algorithm that always picks the job with the earliest end time
D. Dynamic programming based on sorting jobs by start time and using prefix sums

Solution

  1. Step 1: Understand job scheduling constraints

    The problem requires selecting non-overlapping jobs to maximize profit, which is a classic weighted interval scheduling problem.
  2. Step 2: Identify the optimal approach

    Sorting jobs by end time allows binary searching for the last compatible job, enabling a DP solution that builds optimal profit incrementally.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Greedy fails on overlapping jobs with higher profit; DP with binary search handles all cases optimally [OK]
Hint: Sort by end time and use DP with binary search [OK]
Common Mistakes:
  • Assuming greedy by earliest end time always works
  • Sorting by start time only
  • Trying brute force without pruning
3. You are given a set of positive integers and need to partition it into two subsets such that the absolute difference of their sums is minimized. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Greedy algorithm that sorts and assigns elements alternately to subsets
B. Dynamic programming using a subset-sum style approach to find achievable sums
C. Divide and conquer by recursively splitting the array into halves
D. Sorting and then pairing elements from opposite ends to balance sums

Solution

  1. Step 1: Understand problem constraints

    The problem requires minimizing the difference between sums of two subsets, which is a classic partition problem variant.
  2. Step 2: Identify algorithmic pattern

    Greedy or divide-and-conquer approaches do not guarantee minimal difference. Dynamic programming, specifically subset-sum style DP, can find all achievable sums up to total_sum, enabling minimal difference calculation.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    DP subset-sum approach guarantees optimal partition [OK]
Hint: Minimal difference requires subset-sum DP, not greedy [OK]
Common Mistakes:
  • Assuming greedy or sorting suffices for minimal difference
4. The following code attempts to count the number of combinations to make change. Which line contains a subtle bug that causes it to count permutations instead of combinations?
medium
A. Line 5: inner loop iterating backwards over amounts
B. Line 4: outer loop over coins
C. Line 2: dp initialization
D. Line 6: updating dp[w] with dp[w - coin]

Solution

  1. Step 1: Understand iteration order effect

    Iterating amounts backwards causes dp to count permutations, not combinations.
  2. Step 2: Identify bug line

    Line 5 iterates w from amount down to coin, which breaks combination counting logic.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Forward iteration over amounts is required to count combinations correctly [OK]
Hint: Check direction of inner loop iteration [OK]
Common Mistakes:
  • Using backward iteration in 1D dp
  • Misplacing dp[0] initialization
5. What is the time complexity of the space-optimized bottom-up DP solution for Last Stone Weight II, where n is the number of stones and sum is the total weight of all stones?
medium
A. O(n + sum)
B. O(n^2)
C. O(n * sum * log n)
D. O(n * sum)

Solution

  1. Step 1: Identify loops in the code

    Outer loop runs n times (for each stone), inner loop runs up to half the total sum (sum/2).
  2. Step 2: Calculate total operations

    Each iteration updates dp array, so total operations ≈ n * (sum/2) -> O(n * sum).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DP complexity depends on n and sum, not n squared or log factors [OK]
Hint: DP loops over stones and sums -> O(n * sum) [OK]
Common Mistakes:
  • Confusing n with sum leading to O(n^2)
  • Assuming logarithmic factor due to sorting
  • Ignoring that dp array size depends on sum