> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# 4 Keys Keyboard Python Solution with Tests

> Tested Python solution for LeetCode 651 with 30 pytest cases. Generate a practice environment with lcpy.

LeetCode 651, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [Dynamic Programming](/catalog/topics/dynamic-programming). [View on LeetCode](https://leetcode.com/problems/four-keys-keyboard/description/).

Generate this problem as a practice environment: tested reference solution, 30 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 651   # by problem number
lcpy gen -s four_keys_keyboard   # by problem name
```

## 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*.

### Examples

```
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
```

```
Input: n = 7
Output: 9
Explanation: We can at most get 9 A's on screen by pressing the following key sequence: A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
```

### Constraints

* `1 <= n <= 50`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/four_keys_keyboard/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/four_keys_keyboard/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2)
    # Space: O(n)
    def max_a(self, n: int) -> int:
        dp = list(range(n + 1))
        for i in range(3, n + 1):
            for j in range(2, i - 1):
                dp[i] = max(dp[i], dp[j - 1] * (i - j))
        return dp[n]
```

## Complexity

| Time | Space |
| - | - |
| O(n^2) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.