Dynamic Programming21 sections · 916 units
Open in Course

The Problem

When naive DP times out

Some DP transitions look like this: dp[i]=minj=iki1(dp[j])+cost[i]dp[i] = \min_{j=i-k}^{i-1}(dp[j]) + cost[i]. You need the minimum over the last kk states. The naive approach checks all kk candidates for each ii, giving you O(nk)O(nk) time.

When n=105n = 10^5 and k=104k = 10^4, that's a billion operations. Your code times out. You need a way to track the minimum without rechecking all candidates every time. What if you could maintain a "shortlist" of candidates that might become optimal?