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?- A. 30
- B. 25
- C. 36
- 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
- Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed. python def robline(a): take…
- Problem: Each person is [h, k]: height h, and exactly k people in front are at least as tall. Rebuild the queue (sort tallest first…
- Problem: 2n people must be split so n fly to city A and n to city B; costs[i] = [costA, costB]. Minimise total cost (sort by costA −…
- Problem: Can the cards be split into groups of W consecutive values? python from collections import Counter def straights(hand, W): if…
- Problem: Report the median of every window of size k (sorted-list version with bisect). python from bisect import insort, bisectleft def…
- Problem: A single-threaded CPU receives tasks [enqueueTime, processingTime]. When idle it runs the available task with the shortest…