Minimum cost to reach end of array array when a maximum jump of K index is allowed | Java implementation of the approach ; 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
import java . util . * ; class GfG { static int FindMinimumCost ( int ind , int a [ ] , int n , int k , int dp [ ] ) { if ( ind == ( n - 1 ) ) return 0 ; else if ( dp [ ind ] != - 1 ) return dp [ ind ] ; else { int ans = Integer . MAX_VALUE ; for ( int 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 ; } } public static void main ( String [ ] args ) { int a [ ] = { 10 , 30 , 40 , 50 , 20 } ; int k = 3 ; int n = a . length ; int dp [ ] = new int [ n ] ; Arrays . fill ( dp , - 1 ) ; System . out . println ( FindMinimumCost ( 0 , a , n , k , dp ) ) ; } }