Minimum cost to reach end of array array when a maximum jump of K index is allowed | Function for returning the min of two elements ; for calculating the number of elements ; Allocating Memo table and initializing with INT_MAX ; Base case ; For every element relax every reachable element ie relax next k elements ; reaching next k element ; Relaxing the element ; return the last element in the array ; Driver Code
function min ( a , b ) { return ( a > b ) ? b : a ; } function minCostJumpsDP ( A , k ) { let size = A . length ; let x = new Array ( size ) ; for ( let i = 0 ; i < size ; i ++ ) x [ i ] = Number . MAX_VALUE ; x [ 0 ] = 0 ; for ( let i = 0 ; i < size ; i ++ ) { for ( let j = i + 1 ; j < i + k + 1 && j < size ; j ++ ) { x [ j ] = min ( x [ j ] , x [ i ] + Math . abs ( A [ i ] - A [ j ] ) ) ; } } return x [ size - 1 ] ; } let input = [ 83 , 26 , 37 , 35 , 33 , 35 , 56 ] ; document . write ( minCostJumpsDP ( input , 3 ) ) ;