fill the table in bottom - up fashion
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 ] ; }