Minimum cost to reach end of array array when a maximum jump of K index is allowed | C # implementation of the above 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
using System ; 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 = int . MaxValue ; 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 ( ) { int [ ] a = { 10 , 30 , 40 , 50 , 20 } ; int k = 3 ; int n = a . Length ; int [ ] dp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = - 1 ; Console . WriteLine ( FindMinimumCost ( 0 , a , n , k , dp ) ) ; } }