Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Travel on given days; passes cost costs[0] (1 day), costs[1] (7 days) and costs[2] (30 days). Minimise the total cost.

Problem: Travel on given days; passes cost costs[0] (1 day), costs[1] (7 days) and costs[2] (30 days). Minimise the total cost.
def mincost(days, costs):
    s = set(days); last = days[-1]; dp = [0] * (last + 1)
    for d in range(1, last + 1):
        if d not in s: dp[d] = dp[d-1]; continue
        dp[d] = min(dp[d-1] + costs[0], dp[max(0, d-7)] + costs[1], dp[max(0, d-30)] + costs[2])
    return dp[last]
print(mincost([1, 2, 3, 5, 9, 10, 11, 12, 13, 20, 25, 30], [3, 10, 25]))
What is printed?
  1. A. 30
  2. B. 25
  3. C. 36
  4. D. 28

Correct answer: B. 25

dp[d] = cheapest cover of all travel days up to d. Buying the 30-day pass costs 25 for all 12 days, while mixing 7-day and 1-day passes costs more (e.g. 10 + 10 + 3 + 3 + 3 = 29). The DP returns 25, matching a recursive search.

More Coding Interview Problems questions

Exams that ask this topic