Similar Problems

Similar Problems not available

4 Keys Keyboard - Leetcode Solution

Companies:

LeetCode:  4 Keys Keyboard Leetcode Solution

Difficulty: Medium

Topics: math dynamic-programming  

Problem Statement:

Imagine you have a special keyboard with the following keys: Key 1: (A): Print one 'A' on screen. Key 2: (Ctrl-A): Select the whole screen. Key 3: (Ctrl-C): Copy selection to buffer. Key 4: (Ctrl-V): Print buffer on screen appending it.

Now, you can only press the keyboard for N times (with the above four keys), find out the maximum numbers of 'A' you can print on the screen.

Example 1:

Input: N = 3 Output: 3 Explanation: We can at most get 3 'A' on the screen by pressing following key sequence: A, A, A Example 2:

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

1 <= N <= 50 Answers will be in the range of 32-bit signed integer.

Solution:

The approach to solving this problem involves using Dynamic Programming.

We need to start by understanding the problem and breaking it down.

First, we can only print 'A' using the A key. So, every time we press A, we increment the number of A's printed.

However, pressing Ctrl-A, Ctrl-C, Ctrl-V does not result in any A being printed on the screen.

Thus, our goal is to find the maximum number of A's that we can print, by coming up with an optimal sequence.

We can start by creating an array of size N+1, named dp, where dp[i] represents the maximum number of A's we can print using i keystrokes.

To compute dp[N], we need to consider two cases:

If we press A, we increment the number of A's printed by 1, and the remaining keystrokes we have is i-1. Thus, we can compute dp[i] as dp[i-1] + 1.

If we press Ctrl-A, Ctrl-C, and Ctrl-V, the remaining keystrokes will be i-3. Thus, as we only copy and paste the buffer, we can repeat the sequence copied in the buffer multiple times to ensure that we end up with maximum number of A's printed. To be precise, we paste A's for (i-3-j) times after pasting the buffer j times. Let us consider how for j = 1, i.e. we paste the buffer only once, we can compute dp[i] as dp[i-3] * 2.

We can combine both the above cases to compute the maximum number of A's we can print using the same keystroke.

The implementation of this algorithm would look like:

class Solution { public int maxA(int N) { int[] dp = new int[N+1]; dp[0] = 0; for(int i=1; i<=N; i++){ dp[i] = dp[i-1] + 1; // case 1 for(int j=2; j<i; j++){ // for case 2 dp[i] = Math.max(dp[i], dp[j-2] * (i-j+1)); } } return dp[N]; } }

Time Complexity:

The time complexity of this approach is O(N^2), as we need to compute every value of dp[i], with i varying from 1 to N.

Space Complexity:

The space complexity of this approach is also O(N), as we only need to store the values of dp array.

4 Keys Keyboard Solution Code

1