Minimum time to write characters using insert , delete and copy operation | method returns minimum time to write ' N ' characters ; declare dp array and initialize with zero ; first char will always take insertion time ; loop for ' N ' number of times ; if current char count is even then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy ; if current char count is odd then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy and one extra character deletion ; Driver code
function minTimeForWritingChars ( N , insert , remove , copy ) { if ( N == 0 ) return 0 ; if ( N == 1 ) return insert ; let dp = new Array ( N + 1 ) ; for ( let i = 0 ; i < N + 1 ; i ++ ) dp [ i ] = 0 ; dp [ 1 ] = insert ; for ( let i = 2 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) dp [ i ] = Math . min ( dp [ i - 1 ] + insert , dp [ parseInt ( i / 2 , 10 ) ] + copy ) ; else dp [ i ] = Math . min ( dp [ i - 1 ] + insert , dp [ parseInt ( ( i + 1 ) / 2 , 10 ) ] + copy + remove ) ; } return dp [ N ] ; } let N = 9 ; let insert = 1 , remove = 2 , copy = 1 ; document . write ( minTimeForWritingChars ( N , insert , remove , copy ) ) ;