leetcode
  • LeetCode Problems
  • Array
    • Array Partition I
    • Toeplitz Matrix
    • Find All Numbers Disappeared in an Array
    • Max Area of Island
    • Move Zeros
    • Two Sum II - Input array is sorted
    • Degree of an Array
    • Image Smoother
    • Positions of Large Groups
    • Missing Number
    • Maximum Product of Three Numbers
    • Min Cost Climbing Stairs
    • Longest Continuous Increasing Subsequence
    • Remove Element
    • Pascal's Triangle
    • Maximum Subarray
    • Largest Number At Least Twice of Others
    • Search Insert Position
    • Plus One
    • Find Pivot Index
    • Pascal's Triangle II
    • Two Sum
    • Maximize Distance to Closest Person
    • Maximum Average Subarray I
    • Remove Duplicates from Sorted Array
    • Magic Squares In Grid
    • Contains Duplicate II
    • Merge Sorted Array
    • Can Place Flowers
    • Shortest Unsorted Continuous Subarray
    • K-diff Pairs in an Array
    • Third Maximum Number
    • Rotate Array
    • Non-decreasing Array
    • Find All Duplicates in an Array
    • Teemo Attacking
    • Beautiful Arrangement II
    • Product of Array Except Self
    • Max Chunks To Make Sorted
    • Subsets
    • Best Time to Buy and Sell Stock with Transaction Fee
    • Combination Sum III
    • Find the Duplicate Number
    • Unique Paths
    • Rotate Image
    • My Calendar I
    • Spiral Matrix II
    • Combination Sum
    • Task Scheduler
    • Valid Triangle Number
    • Minimum Path Sum
    • Number of Subarrays with Bounded Maximum
    • Insert Delete GetRandom O(1)
    • Find Minimum in Rotated Sorted Array
    • Sort Colors
    • Find Peak Element
    • Subarray Sum Equals K
    • Subsets II
    • Maximum Swap
    • Remove Duplicates from Sorted Array II
    • Maximum Length of Repeated Subarray
    • Image Overlap
    • Length of Longest Fibonacci Subsequence
  • Contest
    • Binary Gap
    • Advantage Shuffle
    • Minimum Number of Refueling Stops
    • Reordered Power of 2
  • Dynamic Programming
    • Climbing Stairs
    • Range Sum Query - Immutable
    • Counting Bits
    • Arithmetic Slices
    • Palindromic Substrings
    • Minimum ASCII Delete Sum for Two Strings
    • Maximum Length of Pair Chain
    • Integer Break
    • Shopping Offers
    • Count Numbers with Unique Digits
    • 2 Keys Keyboard
    • Predict the Winner
    • Stone Game
    • Is Subsequence
    • Delete and Earn
    • Longest Palindromic Subsequence
    • Target Sum
    • Unique Binary Search Trees
    • Minimum Path Sum
    • Combination Sum IV
    • Best Time to Buy and Sell Stock with Cooldown
    • Largest Sum of Averages
    • Largest Plus Sign
    • Untitled
  • Invert Binary Tree
  • Intersection of Two Arrays
  • Surface Area of 3D Shapes
  • K Closest Points to Origin
  • Rotting Oranges
  • Smallest Integer Divisible by K
  • Duplicate Zeros
  • DI String Match
  • Implement Queue using Stacks
  • Increasing Order Search Tree
  • Reveal Cards In Increasing Order
  • Reshape the Matrix
  • Partition List
  • Total Hamming Distance
  • Validate Binary Search Tree
  • Decode Ways
  • Construct Binary Tree from Preorder and Inorder Traversal
  • Construct Binary Search Tree from Preorder Traversal
  • Design Circular Queue
  • Network Delay Time
  • Most Frequent Subtree Sum
  • Asteroid Collision
  • Binary Tree Inorder Traversal
  • Check If Word Is Valid After Substitutions
  • Construct Binary Tree from Preorder and Postorder Traversal
  • K-Concatenation Maximum Sum
Powered by GitBook
On this page
  • Description
  • Solutions
  • My solution
  • Optimal solution
  1. Dynamic Programming

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.

class Solution {
public:
    int minSteps(int n) {
        if(n == 1) return 0;
        // previous action must be paste
        int min_step = 1000;
        for(int m = 1; 2 * m <= n; ++m){
            // paste m characters
            int step = minSteps(n - m, m);
            if(step < min_step)
                min_step = step;
        }
        return min_step + 1;
    }
    
    // n 'A's on the notepad, m 'A's on the clipboard
    int minSteps(int n, int m){
        if(n < m){
            // not possible
            return 1000;
        }else if(n > m){
            // previous action must be paste, i.e., paste m 'A's
            return minSteps(n - m, m) + 1;
        }else{
            // must be copy
            return minSteps(n) + 1;
        }
    }
};

Dynamic programming solution.

class Solution {
public:
    int minSteps(int n) {
        vector<int> dp1(n + 1, n); // dp1[i] = minimum steps to get i 'A's on the notepad.
        dp1[1] = 0;
        // dp2[i][j] = minimum steps to get i 'A's on the notepad and j 'A's on the clipboard
        vector<vector<int>> dp2(n + 1, vector<int>(n + 1, n));
        for(int i = 1; i <= n; ++i){
            for(int j = 1; 2 * j <= i; ++j){
                dp2[i][j] = dp2[i - j][j] + 1; // paste j 'A'
                dp1[i] = min(dp1[i], dp2[i][j]);
            }
            dp2[i][i] = dp1[i] + 1; // copy i 'A' to the clipboard
        }
        return dp1[n];
    }
};

Optimal solution

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

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

class Solution {
public:
    int minSteps(int n) {
        int count = 0;
        for(int i = 2; i <= n; ++i){
            while(n % i == 0){
                count += i;
                n /= i;
            }
        }
        return count;
    }
};
PreviousCount Numbers with Unique DigitsNextPredict the Winner

Last updated 6 years ago

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

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

If i==ji == ji==j, dp[i,j]=dp[i,i]=dp[i]+1.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 > ji>j, dp[i,j]=dp[i−j,j]+1dp[i,j]=dp[i-j,j] + 1dp[i,j]=dp[i−j,j]+1. (+1 for the paste operation)

Say these groups have lengths l1,l2,⋯ ,lml_1,l_2, \cdots, l_ml1​,l2​,⋯,lm​. After performing the moves in the first group, there are l1l_1l1​ As. After performing the moves in the second group, there are l1⋅l2l_1 \cdot l_2l1​⋅l2​ As. At the end, there are l1⋅l2⋅…⋅lm=nl_1 \cdot l_2 \cdot \ldots \cdot l_m = nl1​⋅l2​⋅…⋅lm​=n As.

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