![]() |
VOOZH | about |
Imagine you have a special keyboard with the following keys:
Find maximum numbers of A's that can be produced by pressing keys on the special keyboard N times.
Examples:
Input: n = 3
Output: 3
Explanation: Press key 1 three times.
Input: n = 7
Output: 9
Explanation: The best key sequence is key 1, key 1, key 1, key 2, key 3, key4, key 4.
Below are few important points to note.
a) For n < 7, the output is n itself.
b) Ctrl V can be used multiple times to print current buffer. The idea is to compute the optimal string length for n keystrokes by using a simple insight. The sequence of n keystrokes which produces an optimal string length will end with a suffix of Ctrl-A, a Ctrl-C, followed by only Ctrl-V's . (For n > 6)
Table of Content
First we need to keep pressing A to build some text, but after a point it becomes important to stop typing and start using copy-paste. Copy-paste works like multiplication—if you already have some A’s on the screen, pasting adds the same block again and again, growing much faster than typing one by one. So the goal is to decide the best moment to stop typing (the breakpoint), then do Ctrl-A, Ctrl-C, and use the remaining steps for Ctrl-V to multiply your existing A’s as much as possible.
The idea is to try all such possible stopping points using recursion and pick the one that gives the maximum result.
9
In the below diagram, ok() refers to optimalKeys(n)
In the recursive solution, there are many overlapping subproblems as we can see from the above diagram. These values get recomputed many times, which increases time complexity. So instead of solving them repeatedly, we store the answer the first time we compute it and reuse it whenever needed. This is called Memoization (Dynamic Programming). By doing this, we avoid computing unnecessary repeating states and this improves time complexity from exponential to polynomial.
9
After building some A’s, we use Ctrl-A and Ctrl-C once, then Ctrl-V to multiply the result. However, doing too many pastes is not optimal—it's often better to restart the copy process for a bigger gain. Hence, we only consider the most effective cases: 1, 2, or 3 pastes. Taking the maximum of these captures the optimal solution efficiently without checking all breakpoints.
Consider the following dry run : n = 7
For i = 1 --> screen[0] = 1
For i = 2 --> screen[1] = 2
For i = 3 --> screen[2] = 3
For i = 4 --> screen[3] = 4
For i = 5 --> screen[4] = 5
For i = 6 --> screen[5] = 6
For i = 7 --> screen[6] = max(2 × screen[3], 3 × screen[2], 4 × screen[1]) = max(2 × 4, 3 × 3, 4 × 2) = max(8, 9, 8) = 9
Finally, screen = [1, 2, 3, 4, 5, 6, 9]
Final answer : 9
9