Road-Trip Hotel Stops
You are going on a long trip. You start on the road at mile post 0. Along the way there are n hotels, at mile posts a[1] < a[2] < … < a[n], where each a[i] is measured from the starting point. The only places you are allowed to stop are at these hotels, but you can choose which of the hotels you stop at. You must stop at the final hotel (at distance a[n]), which is your destination.
You'd ideally like to travel 200 miles a day, but this may not be possible. If you travel x miles during a day, the penalty for that day is (200 − x)². You want to plan your trip so as to minimize the total penalty — the sum, over all travel days, of the daily penalties. Design a dynamic-programming algorithm that determines the optimal sequence of hotels at which to stop.
Define a[0] = 0 and let penalty(j, i) = (200 − (a[i] − a[j]))² be the cost of driving straight from hotel j to hotel i.
The last leg arrives at i from some earlier hotel j; try every j and add that leg's penalty to the best trip ending at j. Same "scan all earlier indices" shape as LIS.
The answer is T(n) — not max/min over the table — because you are required to end at hotel n. Read the problem's fixed-endpoint condition before deciding your extraction step.
Optional pseudocode not required by Ed #9
A mechanical translation of the recurrence. The exam grades the recurrence, not this.
function Hotels(a[1..n]): # a[0] = 0 (start) T[0] = 0 for i = 1 to n: T[i] = ∞ for j = 0 to i-1: T[i] = min(T[i], T[j] + (200 - (a[i]-a[j]))^2) return T[n]
Try it yourself
worked example + self-testRecurrence: T(0)=0; T(i)=min{T(j)+(200−(a[i]−a[j]))²}. Answer T(n).
Start mile 0. Hotels a = [180, 340, 360, 540, 700] (indices 1..5). Leg penalty = (200 − distance)².
180, 360, 540, 700 — hotel 340 is skipped. At hotel 360 the DP rejects arriving from 340 (a tiny 20-mile leg → penalty 32400) in favor of driving 180→360. For contrast, stopping at every hotel costs 36400 — 13× worse.Start mile 0. Hotels a = [250, 300, 550, 780]. Same (200 − distance)² penalty; must end at 780.