How to print maximum number of A 's using given four keys | This function returns the optimal length string for N keystrokes ; The optimal string length is N when N is smaller than 7 ; An array to store result of subproblems ; To pick a breakpoint ; Initializing the optimal lengths array for uptil 6 input strokes ; Solve all subproblems in bottom manner ; Initialize length of optimal string for n keystrokes ; For any keystroke n , we need to loop from n - 3 keystrokes back to 1 keystroke to find a breakpoint ' b ' after which we will have ctrl - a , ctrl - c and then only ctrl - v all the way . ; If the breakpoint is at b 'th keystroke then  the optimal string would  have length  (n-b-1)*screen[b-1]; ; Driver code ; for the rest of the array we will rely on the previous entries to compute new ones
function findoptimal ( N ) { if ( N <= 6 ) return N ; let screen = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) { screen [ i ] = 0 ; } let b ; let n ; for ( n = 1 ; n <= 6 ; n ++ ) screen [ n - 1 ] = n ; for ( n = 7 ; n <= N ; n ++ ) { screen [ n - 1 ] = 0 ; for ( b = n - 3 ; b >= 1 ; b -- ) { let curr = ( n - b - 1 ) * screen [ b - 1 ] ; if ( curr > screen [ n - 1 ] ) screen [ n - 1 ] = curr ; } } return screen [ N - 1 ] ; } let N ; for ( N = 1 ; N <= 20 ; N ++ ) document . write ( " " + N + " " + findoptimal ( N ) + " " ) ;