Minimize cost of choosing and skipping array elements to reach end of the given array | Function to find the minimum cost to reach the end of the array from the first element ; Store the results ; Consider first index cost ; Find answer for each position i ; First Element ; Second Element ; For remaining element ; Consider min cost for skipping ; Last index represents the minimum total cost ; Given X ; Given array cost [ ] ; Function Call
function minimumCost ( cost , n , x ) { let dp = [ ] ; dp [ 0 ] = cost [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { if ( i == 1 ) dp [ i ] = cost [ i ] + dp [ i - 1 ] ; if ( i == 2 ) dp [ i ] = cost [ i ] + Math . min ( dp [ i - 1 ] , x + dp [ i - 2 ] ) ; if ( i >= 3 ) dp [ i ] = cost [ i ] + Math . min ( dp [ i - 1 ] , Math . min ( x + dp [ i - 2 ] , 2 * x + dp [ i - 3 ] ) ) ; } document . write ( dp [ n - 1 ] ) ; } let X = 4 ; let cost = [ 6 , 3 , 9 , 2 , 1 , 3 ] ; let N = cost . length ; minimumCost ( cost , N , X ) ;