4 Keys Keyboard - Problem

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.

Input & Output

Example 1 — Small Input
$ Input: n = 7
Output: 9
💡 Note: Best sequence: A-A-A-Ctrl+A-Ctrl+C-Ctrl+V-Ctrl+V (3 A's × 3 = 9 A's total)
Example 2 — Very Small Input
$ Input: n = 3
Output: 3
💡 Note: Just press A three times: A-A-A gives 3 A's
Example 3 — Larger Input
$ Input: n = 9
Output: 12
💡 Note: Optimal sequence uses copy-paste: A-A-A-A-Ctrl+A-Ctrl+C-Ctrl+V-Ctrl+V-Ctrl+V (4 A's × 3 = 12 A's total)

Constraints

  • 1 ≤ n ≤ 50
  • All key presses must be valid keyboard operations

Visualization

Tap to expand
4 Keys Keyboard Problem INPUT Special Keyboard A Print 'A' Ctrl-A Select All Ctrl-C Copy Ctrl-V Paste Input: n = 7 Max key presses: 7 Goal: Maximize 'A's Find optimal sequence ALGORITHM STEPS 1 Define dp[i] Max A's with i presses 2 Base: dp[i] = i Press A i times 3 Try Ctrl-A,C,V At position j, paste 4 Recurrence dp[i]=dp[j]*(i-j-1) DP Table for n=7 i: dp: 1234567 123456 9 Optimal: AAA Ctrl-A Ctrl-C Ctrl-V Ctrl-V Time: O(n^2) Space: O(n) Try all break points j FINAL RESULT Optimal Sequence (n=7) 1. AScreen: A 2. AScreen: AA 3. AScreen: AAA 4. Ctrl-A[Select] 5. Ctrl-C[Copy] 6. Ctrl-VAAAAAA 7. Ctrl-VAAAAAAAAA 3 + 3 + 3 = 9 A's Output: 9 OK - Verified! Max A's in 7 presses Key Insight: For n > 6, copying and pasting becomes more efficient than just pressing 'A'. The optimal strategy is to find the best "break point" j where we select, copy, then paste (i-j-1) times. This multiplies dp[j] by (i-j-1), giving us dp[j] * (i-j-1) characters. TutorialsPoint - 4 Keys Keyboard | Optimal Solution (Dynamic Programming)
Asked in
Google 45 Microsoft 30 Amazon 25
18.7K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen