Imagine you have a special keyboard with the following keys:
- Key 1: Prints ‘A’ on screen
- Key 2: (Ctrl-A): Select screen
- Key 3: (Ctrl-C): Copy selection to buffer
- Key 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed.
Find maximum numbers of A’s that can be produced by pressing keys on the special keyboard N times.
- Time : O(2^n)
- Space : O(2^n)
c++
1 | class Solution{ |
- Time : O(n)
- Space : O(n)
As the number of A’s become large, the effect of pressing Ctrl-V more than 3 times starts to become insubstantial as compared to just pressing Ctrl-A, Ctrl-C and Ctrl-V again.
So We just calculate last 3 copy & paste operation
c++
1 | class Solution{ |