Minimum cost to reach end of array array when a maximum jump of K index is allowed | Java implementation of the approach ; 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
import java . util . * ; class GFG { static int min ( int a , int b ) { return ( a > b ) ? b : a ; } static int minCostJumpsDP ( int [ ] A , int k ) { int size = A . length ; int [ ] x = new int [ size ] ; Arrays . fill ( x , Integer . MAX_VALUE ) ; x [ 0 ] = 0 ; for ( int i = 0 ; i < size ; i ++ ) { for ( int 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 ] ; } public static void main ( String [ ] args ) { int [ ] input = { 83 , 26 , 37 , 35 , 33 , 35 , 56 } ; System . out . println ( minCostJumpsDP ( input , 3 ) ) ; } }