4 Keys Keyboard — LeetCode 651 Python Solution

MediumLeetCode PremiumMathDynamic Programming
Problem
#651
Reading time
2 min

The problem

Imagine you have a special keyboard with the following keys: A: Print one 'A' on the screen. Ctrl-A: Select the whole screen.

Example

Input
n = 3
Output
3
Explanation
We can at most get 3 A's on screen by pressing the following key sequence:

Python solution

Python
class Solution:
    def maxA(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[-1]

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 651. 4 Keys Keyboard is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 651. 4 Keys Keyboard?
LeetCode 651. 4 Keys Keyboard is rated Medium on LeetCode.
What topics does LeetCode 651. 4 Keys Keyboard cover?
LeetCode 651. 4 Keys Keyboard is tagged Math and Dynamic Programming on LeetCode.
Is LeetCode 651. 4 Keys Keyboard a premium problem?
Yes. LeetCode 651. 4 Keys Keyboard is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview