text: Minimize cost to reach end of an array by two forward jumps or one backward jump in each move | Function to find the minimum cost to reach the end of an array ; Base Case : When N < 3 ; Store the results in table ; Initialize base cases ; Iterate over the range [ 2 , N - 2 ] to construct the dp array ; Handle case for the last index , i . e . N - 1 ; Prlet the answer ; Driver Code
code: function minCost ( arr , n ) { if ( n < 3 ) { document . write ( arr [ 0 ] ) ; return ; } let dp = [ ] ; dp [ 0 ] = arr [ 0 ] ; dp [ 1 ] = dp [ 0 ] + arr [ 1 ] + arr [ 2 ] ; for ( let i = 2 ; i < n - 1 ; i ++ ) dp [ i ] = Math . min ( dp [ i - 2 ] + arr [ i ] , dp [ i - 1 ] + arr [ i ] + arr [ i + 1 ] ) ; dp [ n - 1 ] = Math . min ( dp [ n - 2 ] , dp [ n - 3 ] + arr [ n - 1 ] ) ; document . write ( dp [ n - 1 ] ) ; } let arr = [ 9 , 4 , 6 , 8 , 5 ] ; let N = arr . length ; minCost ( arr , N ) ;