Minimum cost to reach end of array array when a maximum jump of K index is allowed

Given an array arr[] of N integers and an integer K, one can move from an index i to any other j if j ≤ i + k. The cost of moving from one index i to the other index j is abs(arr[i] – arr[j]). Initially we start from the index 0 and we need to reach the last index i.e. N – 1. The task is to reach the last index in the minimum cost possible.

Examples:

Input: arr[] = {10, 30, 40, 50, 20}, k = 3
Output: 30
0 -> 1 -> 4
the total cost will be: |10-30| + |30-20| = 30

Input: arr[] = {40, 10, 20, 70, 80, 10}, k = 4
Output: 30



Approach: The problem can be solved using Dynamic Programming. We start from index 0 and we can visit any of the index from i+1 to i+k, hence the minimum cost of all the paths will be stored in dp[i]. Once we reach N-1, it will be our base case. Use memoization to memoize the states, so that we do not need to revisit the state again to reduce complexity.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the minimum cost
// to reach the last index
int FindMinimumCost(int ind, int a[],
                    int n, int k, int dp[])
{
  
    // If we reach the last index
    if (ind == (n - 1))
        return 0;
  
    // Already visited state
    else if (dp[ind] != -1)
        return dp[ind];
    else {
  
        // Initially maximum
        int ans = INT_MAX;
  
        // Visit all possible reachable index
        for (int i = 1; i <= k; i++) {
  
            // If inside range
            if (ind + i < n)
                ans = min(ans, abs(a[ind + i] - a[ind])
                          + FindMinimumCost(ind + i, a,
                                             n, k, dp));
  
            // We cannot move any further
            else
                break;
        }
  
        // Memoize
        return dp[ind] = ans;
    }
}
  
// Driver Code
int main()
{
    int a[] = { 10, 30, 40, 50, 20 };
    int k = 3;
    int n = sizeof(a) / sizeof(a[0]);
    int dp[n];
    memset(dp, -1, sizeof dp);
    cout << FindMinimumCost(0, a, n, k, dp);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GfG 
  
// Function to return the minimum cost 
// to reach the last index 
static int FindMinimumCost(int ind, int a[], 
                        int n, int k, int dp[]) 
  
    // If we reach the last index 
    if (ind == (n - 1)) 
        return 0
  
    // Already visited state 
    else if (dp[ind] != -1
        return dp[ind]; 
    else
  
        // Initially maximum 
        int ans = Integer.MAX_VALUE; 
  
        // Visit all possible reachable index 
        for (int i = 1; i <= k; i++)
        
  
            // If inside range 
            if (ind + i < n) 
                ans = Math.min(ans, Math.abs(a[ind + i] - a[ind]) + 
                            FindMinimumCost(ind + i, a, n, k, dp)); 
  
            // We cannot move any further 
            else
                break
        
  
        // Memoize 
        return dp[ind] = ans; 
    
  
// Driver Code 
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)); 
}
  
// This code is contributed by Prerna Saini

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the approach
import sys
  
# Function to return the minimum cost
# to reach the last index
def FindMinimumCost(ind, a, n, k, dp):
      
    # If we reach the last index
    if (ind == (n - 1)):
        return 0
  
    # Already visited state
    elif (dp[ind] != -1):
        return dp[ind]
    else:
          
        # Initially maximum
        ans = sys.maxsize
  
        # Visit all possible reachable index
        for i in range(1, k + 1):
              
            # If inside range
            if (ind + i < n):
                ans = min(ans, abs(a[ind + i] - a[ind]) + 
                      FindMinimumCost(ind + i, a, n, k, dp))
  
            # We cannot move any further
            else:
                break
  
        # Memoize
        dp[ind] = ans
        return ans
  
# Driver Code
if __name__ == '__main__':
    a = [10, 30, 40, 50, 20]
    k = 3
    n = len(a)
    dp = [-1 for i in range(n)]
    print(FindMinimumCost(0, a, n, k, dp))
  
# This code is contributed by
# Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach
using System;
  
class GfG 
  
    // Function to return the minimum cost 
    // to reach the last index 
    static int FindMinimumCost(int ind, int []a, 
                            int n, int k, int []dp) 
    
      
        // If we reach the last index 
        if (ind == (n - 1)) 
            return 0; 
      
        // Already visited state 
        else if (dp[ind] != -1) 
            return dp[ind]; 
              
        else
      
            // Initially maximum 
            int ans = int.MaxValue; 
      
            // Visit all possible reachable index 
            for (int i = 1; i <= k; i++)
            
      
                // If inside range 
                if (ind + i < n) 
                    ans = Math.Min(ans, Math.Abs(a[ind + i] - a[ind]) + 
                                FindMinimumCost(ind + i, a, n, k, dp)); 
      
                // We cannot move any further 
                else
                    break
            
      
            // Memoize 
            return dp[ind] = ans; 
        
    
      
    // Driver Code 
    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)); 
    }
}
  
// This code is contributed by Ryuga

chevron_right


PHP

Output:

30

Time Complexity: O(N * K)
Auxiliary Space: O(N)



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.