Minimize total cost without repeating same task in two consecutive iterations | Function to return the minimum cost for N iterations ; Construct the dp table ; 1 st row of dp table will be equal to the 1 st of cost matrix ; Iterate through all the rows ; To iterate through the columns of current row ; Initialize val as infinity ; To iterate through the columns of previous row ; Fill the dp matrix ; Returning the minimum value ; Number of iterations ; Number of tasks ; Cost matrix
function findCost ( cost_mat , N , M ) { var dp = Array ( N ) ; for ( i = 0 ; i < N ; i ++ ) dp [ i ] = Array ( M ) . fill ( 0 ) ; for ( i = 0 ; i < M ; i ++ ) dp [ 0 ] [ i ] = cost_mat [ 0 ] [ i ] ; for ( row = 1 ; row < N ; row ++ ) { for ( curr_col = 0 ; curr_col < M ; curr_col ++ ) { var val = 999999999 ; for ( prev_col = 0 ; prev_col < M ; prev_col ++ ) { if ( curr_col != prev_col ) val = Math . min ( val , dp [ row - 1 ] [ prev_col ] ) ; } dp [ row ] [ curr_col ] = val + cost_mat [ row ] [ curr_col ] ; } } var ans = Number . MAX_VALUE ; for ( i = 0 ; i < M ; i ++ ) ans = Math . min ( ans , dp [ N - 1 ] [ i ] ) ; return ans ; } var N = 4 ; var M = 4 ; var cost_mat = [ [ 4 , 5 , 3 , 2 ] , [ 6 , 2 , 8 , 1 ] , [ 6 , 2 , 2 , 1 ] , [ 0 , 5 , 5 , 1 ] ] ; document . write ( findCost ( cost_mat , N , M ) ) ;