4 Keys Keyboard Problem
Description
LeetCode Problem 651.
Imagine you have a special keyboard with the following keys:
- A: Print one
'A'on the screen. - Ctrl-A: Select the whole screen.
- Ctrl-C: Copy selection to buffer.
- Ctrl-V: Print buffer on screen appending it after what has already been printed.
Given an integer n, return the maximum number of 'A' you can print on the screen with at most n presses on the keys.
Example 1:
Input: n = 3
Output: 3
Explanation: We can at most get 3 A's on screen by pressing the following key sequence:
A, A, A
Example 2:
Input: n = 7
Output: 9
Explanation: We can at most get 9 A's on screen by pressing following key sequence:
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
Constraints:
1 <= n <= 50
Solution
Approach: Dynamic Programming
Ctrl-A and Ctrl-C only pay off as a pair: Ctrl-A selects everything on the screen and Ctrl-C copies it, so together they cost two presses and add nothing yet. After that, every Ctrl-V adds another full copy. So an optimal sequence is some A presses, then a few rounds of "Ctrl-A, Ctrl-C, Ctrl-V, Ctrl-V, ...".
Let dp[i] be the most A's we can have after i presses. Two kinds of last steps are possible:
- Type A every time:
dp[i] = i. - Stop at some earlier point
bwithdp[b]A's, then press Ctrl-A, Ctrl-C and paste with all the remainingi - b - 2presses. The screen then holds the original plusi - b - 2copies, which isdp[b] * (i - b - 1)A's.
Take the largest value over all b from 1 to i - 3 (we need at least one paste for the copy to help). Small n is the tricky part: up to n = 6 typing A's is as good as anything (for n = 6, three A's and one copy-paste round also give 6), and the paste approach wins only from n = 7 on.
Complexity: O(n2) time and O(n) extra space.
class Solution:
def maxA(self, n: int) -> int:
# dp[i] = most A's on screen after i presses. Typing A every time gives i.
dp = list(range(n + 1))
for i in range(3, n + 1):
# Reach dp[b] A's in b presses, then Ctrl-A, Ctrl-C and paste the rest:
# i - b - 2 pastes give dp[b] * (i - b - 1) A's.
for b in range(1, i - 2):
dp[i] = max(dp[i], dp[b] * (i - b - 1))
return dp[n]