Maximum profit by buying and selling a share at most k times | Function to find out maximum profit by buying & selling / a share atmost k times given stock price of n days ; table to store results of subproblems profit [ t ] [ i ] stores maximum profit using atmost t transactions up to day i ( including day i ) ; For day 0 , you can 't earn money  irrespective of how many times you trade ; profit is 0 if we don 't do any  transaction (i.e. k =0) ; fill the table in bottom - up fashion ; Driver code
function maxProfit ( price , n , k ) { var profit = Array ( k + 1 ) . fill ( 0 ) . map ( x => Array ( n + 1 ) . fill ( 0 ) ) ; for ( var i = 0 ; i <= k ; i ++ ) profit [ i ] [ 0 ] = 0 ; for ( j = 0 ; j <= n ; j ++ ) profit [ 0 ] [ j ] = 0 ; for ( var i = 1 ; i <= k ; i ++ ) { var prevDiff = - Number . MAX_VALUE ; for ( var j = 1 ; j < n ; j ++ ) { prevDiff = Math . max ( prevDiff , profit [ i - 1 ] [ j - 1 ] - price [ j - 1 ] ) ; profit [ i ] [ j ] = Math . max ( profit [ i ] [ j - 1 ] , price [ j ] + prevDiff ) ; } } return profit [ k ] [ n - 1 ] ; } var k = 3 ; var price = [ 12 , 14 , 17 , 10 , 14 , 13 , 12 , 15 ] ; var n = price . length ; document . write ( " " + maxProfit ( price , n , k ) ) ;