progress

~/problems / 1-D dynamic programming / Intro DP

Flower cart: station or park

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A flower seller parks her cart each day either outside the train station or by the park gates. On day i she would earn station[i] or park[i]. Moving the cart overnight costs move_fee; day 0 can start at either spot, and staying put is free.

Implement best_earnings(station: list[int], park: list[int], move_fee: int) -> int: the most she can earn after paying for every move.

best_earnings([5, 1, 5], [1, 6, 1], 4)        # 11   stay at the station all three days
                                              #      (chasing the park on day 1 earns 5+6+5 but pays 8 in fees)
best_earnings([3, 3, 3, 3], [1, 9, 9, 1], 2)  # 20   e.g. station, park, park, station: 24 - 4

Picking the better spot each day on its own is not enough, as the first example shows. With no days the answer is 0.

Up to 100,000 days; earnings and move_fee up to 10,000.

⭐ Bonus: a speed test with 100,000 days earns a star in O(n). Trying all 2^n spot sequences is hopeless.

Show hint

keep two running values: the best total if day i ends at the station, and if it ends at the park. Each is that day's earnings plus the better of "was already here" and "was at the other spot, minus move_fee".

Topic: Intro DP. State, transition, base case; top-down memo vs bottom-up table.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc