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]
CodePudding user response:
Explaining the correct recurrence
Having the Nth
operation as print, the N-1
th operation could be either copy or paste.
N-1
th copy,N
th paste.
Copying atN-1
would mean copyingdp[N-2]
characters, so the total here becomes2*dp[N-2]
N-2
th copy,N-1
th paste,N
th paste.
Copying atN-2
would mean copyingdp[N-3]
characters, so the total here becomes3*dp[N-3]
(originaldp[N-3]
pasted twice).N-3
th 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 theN
th operation as a copy or paste.DP[N]=2DP[N-2]
misses the case of two consecutive pastes (hint: First few values in thedp
table are listed, figure out the case fordp[5]
:
i -> dp[i]
0 0
1 1
2 2
3 2
4 4
5 6