We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

4 Keys Keyboard

Number: 651

Difficulty: Medium

Paid? Yes

Companies: Google, Microsoft


Problem Description

Given a special keyboard with four keys (A, Ctrl-A, Ctrl-C, Ctrl-V), determine the maximum number of 'A's that can be produced on the screen with exactly n key presses. The challenge is to choose the optimal sequence of operations (either pressing A or performing a combination of select, copy, and paste) to maximize the output.


Key Insights

  • Break the problem down using dynamic programming by determining the best result for every number of key presses up to n.
  • Instead of pressing A every time, there is an optimal point at which performing a sequence of operations (Ctrl-A, Ctrl-C, and multiple Ctrl-V’s) yields a multiplication effect.
  • For each key press count i, explore previous states where a break in the sequence occurs, i.e., performing a block operation from some previous state j.
  • The optimal solution is given by evaluating dp[i] = max(dp[i-1] + 1, dp[j] * (i - j - 1)) for possible breakpoints j.

Space and Time Complexity

Time Complexity: O(n^2) due to the nested loop for computing the state from previous states. Space Complexity: O(n) for maintaining the dp array.


Solution

We use a dynamic programming approach:

  1. Define dp[i] as the maximum number of 'A's that can be printed with i key presses.
  2. For each i from 1 to n, the simplest approach is to press A which yields dp[i-1] + 1.
  3. For a sequence break, choose a breakpoint j where a block operation (Ctrl-A, Ctrl-C, then multiple Ctrl-V's) starts. This gives dp[i] = max(dp[i], dp[j] * (i - j - 1)). The (i - j - 1) factor comes from the number of paste operations after executing one select-all and one copy.
  4. Return dp[n] as the answer.

This strategy efficiently computes the maximum possible count of ‘A’s leveraging previous computations.


Code Solutions

# Python implementation for the 4 Keys Keyboard problem

def maxA(n):
    # dp[i] will store the maximum number of A's that can be produced with i presses
    dp = [0] * (n + 1)
    
    # Base case: for each press, the simplest option is to press 'A'
    for i in range(1, n + 1):
        dp[i] = dp[i - 1] + 1  # Option 1: Press 'A'
        # Try breaking the sequence into a block operation at position j (i - breakpoint)
        for j in range(i - 3, 0, -1):
            # dp[j] is the count before the block operation
            # (i - j - 1) is the number of times we can paste after copying the sequence
            current = dp[j] * (i - j - 1)
            dp[i] = max(dp[i], current)
    return dp[n]

# Example usage:
if __name__ == "__main__":
    n = 7
    print("Maximum A's for", n, "keypresses:", maxA(n))
← Back to All Questions