'Why this dynamic programming recurrence relation is correct?
Consider you have a screen. Now we can do two operations on the screen:
Copy content on the screen
Paste copied content on the screen
Suppose at the beginning, the clipboard is empty and there is one character on the screen. If we have N operations, how we can print the maximum number of characters on the screen using N operations of copy and pastes?
The answer is
DP[N]=max(2DP[N-2],3DP[N-3])
But how do we get the above result? And why below formulations aren't correct?
DP[N]=max(DP[N-1],2DP[N-2])DP[N]=2DP[N-2]
Solution 1:[1]
Explaining the correct recurrence
Having the Nth operation as print, the N-1th operation could be either copy or paste.
N-1th copy,Nth paste.
Copying atN-1would mean copyingdp[N-2]characters, so the total here becomes2*dp[N-2]N-2th copy,N-1th paste,Nth paste.
Copying atN-2would mean copyingdp[N-3]characters, so the total here becomes3*dp[N-3](originaldp[N-3]+ pasted twice).N-3th copy at 3 pastes wouldn't make sense, since you could get the same result via step 1 twice.
So the result becomes dp[N] = max(2*dp[N-2],3*dp[N-3]).
Issue with your recurrence
DP[N]=max(DP[N-1],2DP[N-2])wouldn't work because there's no way to track if you have theNth operation as a copy or paste.DP[N]=2DP[N-2]misses the case of two consecutive pastes (hint: First few values in thedptable are listed, figure out the case fordp[5]:
i -> dp[i]
0 0
1 1
2 2
3 2
4 4
5 6
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
