4 Keys Keyboard in C++

Suppose we will try to write the letter ‘A’, using the keyboard. Our goal is to use only four keys and try to write maximum ‘A’s on the text field. The keys are ‘A’, ‘C’, ‘V’, and ‘Ctrl’.

To write a maximum number of A, we will use Ctrl + A to select All, Ctrl + C to copy, and Ctrl + V to paste.

So, if the input is like the number of keystrokes is 7 then the output will be 9 as of press A three times.

Then Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+V

To solve this, we will follow these steps −

  • if keyStrokes <= 6, then

    • return keyStrokes

  • for n := 1 to 6, do

    • result[n-1] := n

  • for n := 7 to keyStrokes, do

    • result[n-1] := 0

    • for breakpoint := n-3 down to 1, do

      • curr := (n – breakpoint - 1)*result[breakpoint - 1]

      • if curr > result[n-1], then

        • result[n - 1] := curr

  • result[keyStrokes - 1]


Let us see the following implementation to get a better understanding −

 Live Demo

using namespace std;
int keyNumbers(int keystrokes){ //find number of 'A's using 4 types of keys
   if (keystrokes <= 6) //if keystrokes are less than 7
      return keystrokes;
      int result[keystrokes]; //store intermediate results
      for (int n=1; n<=6; n++) //upto 6 keystrokes, we need that number of keystrokes for max
         result[n-1] = n;
      for (int n=7; n<=keystrokes; n++){ //for 7th to higher result[n-1] = 0; //initially store 0 as result
      for (int breakPoint=n-3; breakPoint>=1; breakPoint--){ //find breakpoint to select, copy and paste
         int curr = (n-breakPoint-1)*result[breakPoint-1];
         if (curr > result[n-1])
            result[n-1] = curr;
   return result[keystrokes-1];
int main(){
   int keystrokes;
   cout << "Enter Number of keystrokes: "; cin >> keystrokes;
   cout << "Maximum Number of A's with "<<keystrokes << " keystrokes
   is: "<< keyNumbers(keystrokes)<<endl;




Enter Number of keystrokes: Maximum Number of A's with 0 keystrokes is: 0

Updated on: 16-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started