2 Keys Keyboard

Description

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).

  2. Paste: You can paste the characters which are copied last time.

Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.

Example 1:

Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Note:

  1. The n will be in the range [1, 1000].

Solutions

My solution

Let dp[i, j] be the minimum number of steps to get i As on the notepad with j As on the clipboard. Let dp[i] be the minimum number of steps to get i As on the notepad.

dp[i]=min0<j<idp[i,j]dp[i] = \min_{0 < j < i} dp[i, j]

dp[i,j]dp[i,j] is undefined if i<ji < j, because the clipboard cannot have more A than the notepad.

If i==ji == j, dp[i,j]=dp[i,i]=dp[i]+1.dp[i,j] = dp[i, i] = dp[i] + 1. (+1 for the copy operation)

If i>ji > j, dp[i,j]=dp[ij,j]+1dp[i,j]=dp[i-j,j] + 1. (+1 for the paste operation)

Dynamic programming solution.

Optimal solution

For any sequence of moves that produces n As, break it into groups of (copy, paste, paste, ..., paste).

Say these groups have lengths l1,l2,,lml_1,l_2, \cdots, l_m. After performing the moves in the first group, there are l1l_1 As. After performing the moves in the second group, there are l1l2l_1 \cdot l_2 As. At the end, there are l1l2lm=nl_1 \cdot l_2 \cdot \ldots \cdot l_m = n As.

If any group has a length that is a composite number, say pqp \cdot q, we can break it into two smaller groups. The first group is 1 copy followed by p1p -1 pastes. And the second group is 1 copy followed by q1q - 1 pastes. The number of moves does not increase because p+qpqp + q \le p \cdot q for p,q2p, q \ge 2.

So the minimum number of moves to get n A s is the sum of the prime factors of n.

Last updated