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 OverviewInput: n=7Available Keys:A, Ctrl+A, Ctrl+C, Ctrl+VOutput: 9 A'sDifferent Strategies:Strategy 1: A-A-A-A-A-A-A → 7 A'sStrategy 2: A-A-A-A-Ctrl+A-Ctrl+C-Ctrl+V → 8 A'sStrategy 3: A-A-A-Ctrl+A-Ctrl+C-Ctrl+V-Ctrl+V → 9 A's ✓Key InsightAfter typing some A's, copy-paste sequence (Ctrl+A, Ctrl+C, multiple Ctrl+V)can multiply the A's more efficiently than continuing to press AMaximum Possible: 9 A's with 7 key presses
Understanding the Visualization
1
Input
n=7 key presses allowed
2
Strategy
Choose between pressing A or copy-paste sequences
3
Output
Maximum 9 A's achievable
Key Takeaway
🎯 Key Insight: The optimal strategy balances between typing A's initially and using copy-paste sequences to multiply them efficiently
Asked in
Google 45 Microsoft 30 Amazon 25
18.5K 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