Minimum cost to reach end of array array when a maximum jump of K index is allowed | Function to return the minimum cost to reach the last index ; If we reach the last index ; Already visited state ; Initially maximum ; Visit all possible reachable index ; If inside range ; We cannot move any further ; Memoize ; Driver Code
function FindMinimumCost ( ind , a , n , k , dp ) { if ( ind == ( n - 1 ) ) return 0 ; else if ( dp [ ind ] != - 1 ) return dp [ ind ] ; else { var ans = Number . MAX_VALUE ; for ( var i = 1 ; i <= k ; i ++ ) { if ( ind + i < n ) ans = Math . min ( ans , Math . abs ( a [ ind + i ] - a [ ind ] ) + FindMinimumCost ( ind + i , a , n , k , dp ) ) ; else break ; } return dp [ ind ] = ans ; } } var a = [ 10 , 30 , 40 , 50 , 20 ] ; var k = 3 ; var n = a . length ; var dp = Array ( n ) . fill ( - 1 ) ; document . write ( FindMinimumCost ( 0 , a , n , k , dp ) ) ;