Dynamic Programming21 sections · 916 units
Open in Course

Toss Strange Coins - Implementation

Space optimization

Full table: O(nk)O(nk) space. But each row only depends on the previous row. Use two arrays: prevprev and currcurr. Swap after each coin. Space: O(k)O(k). Or use single array with reverse iteration: dp[j]=dp[j1]pi+dp[j](1pi)dp[j] = dp[j-1] \cdot p_i + dp[j] \cdot (1-p_i), iterating jj from kk down to 11. Time: O(nk)O(nk), Space: O(k)O(k). The pattern is identical to 0/1 Knapsack space reduction. Space reduction works because each row only depends on the previous row. You can use two arrays or reverse iteration.