Wednesday, July 3, 2024
HomeData ModellingDynamic ProgrammingMinimum cost to reach the end of the array with maximum jumps...

Minimum cost to reach the end of the array with maximum jumps of length K

Given an array arr[] of size N and an integer K, one can move from an index i to any other index j such that j ? i+k. The cost of being at any index ā€˜iā€˜, is arr[i]. The task is to find the minimum cost to reach the end of the array starting from index 0.

Examples:

Input : arr[] = {2, 4, 1, 6, 3}, K = 2
Output: 6
Explanation: Path can be taken as 2 -> 1-> 3 = 6

Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 3
Output: 10
Explanation: Path can be taken as 1->3->6 = 10

Naive Approach: The task can be solved using dynamic programming. Maintain a dp[] array where, where dp[i] indicates the minimum cost required to reach the ith index. Follow the below steps to solve the problem:

  • Traverse all the K elements backward from the current element, & find the minimum dp value and add it to the current answer.
  • So, calculating answer for ith index will be dp[i] = arr[i] + min(dp[j] Ā for all j Ā such that i-k <= j < i) .

Below is the implementation of the above approach:

C++




//Ā  C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
Ā 
//Ā  Function to find the minimum jumps
int solve(vector<int>& arr, int K)
{
Ā Ā int size = arr.size();
Ā Ā vector<int> dp(size, 0);
Ā 
Ā Ā //Ā  Initially only a single element
Ā Ā dp[0] = arr[0];
Ā 
Ā Ā for (int idx = 1; idx < size; idx++) {
Ā 
Ā Ā Ā Ā //Ā  At most k elements backwards
Ā Ā Ā Ā int end = max(-1, idx - K - 1);
Ā Ā Ā Ā int mini = INT_MAX;
Ā 
Ā Ā Ā Ā //Ā  Find minimum among all the values
Ā Ā Ā Ā for (int ptr = idx - 1; ptr > end; ptr--) {
Ā Ā Ā Ā Ā Ā mini = min(mini, dp[ptr]);
Ā Ā Ā Ā }
Ā Ā Ā Ā dp[idx] = arr[idx] + mini;
Ā Ā }
Ā Ā Ā 
Ā Ā //Ā  Return cost to reach the
Ā Ā //Ā  last index of array
Ā Ā return dp[size - 1];
}
Ā 
//Ā  Driver Code
int main()
{
Ā Ā vector<int> arr = { 2, 4, 1, 6, 3 };
Ā Ā int K = 2;
Ā 
Ā Ā int ans = solve(arr, K);
Ā Ā cout << ans << "\n";
}
Ā 
// This code is contributed by Taranpreet


Java




// Java program for the above approach
import java.io.*;
public class GFG {
Ā 
Ā Ā // Function to find the minimum jumps
Ā Ā static int solve(int[] arr, int K) {
Ā Ā Ā Ā int size = arr.length;
Ā Ā Ā Ā int[] dp = new int[size];
Ā 
Ā Ā Ā Ā for (int i = 0; i < size; i++) {
Ā Ā Ā Ā Ā Ā dp[i] = 0;
Ā Ā Ā Ā }
Ā 
Ā Ā Ā Ā // Initially only a single element
Ā Ā Ā Ā dp[0] = arr[0];
Ā 
Ā Ā Ā Ā for (int idx = 1; idx < size; idx++) {
Ā 
Ā Ā Ā Ā Ā Ā // At most k elements backwards
Ā Ā Ā Ā Ā Ā int end = Math.max(-1, idx - K - 1);
Ā Ā Ā Ā Ā Ā int mini = Integer.MAX_VALUE;
Ā 
Ā Ā Ā Ā Ā Ā // Find minimum among all the values
Ā Ā Ā Ā Ā Ā for (int ptr = idx - 1; ptr > end; ptr--) {
Ā Ā Ā Ā Ā Ā Ā Ā mini = Math.min(mini, dp[ptr]);
Ā Ā Ā Ā Ā Ā }
Ā Ā Ā Ā Ā Ā dp[idx] = arr[idx] + mini;
Ā Ā Ā Ā }
Ā 
Ā Ā Ā Ā // Return cost to reach the
Ā Ā Ā Ā // last index of array
Ā Ā Ā Ā return dp[size - 1];
Ā Ā }
Ā 
Ā Ā // Driver Code
Ā Ā public static void main(String args[]) {
Ā Ā Ā Ā int[] arr = { 2, 4, 1, 6, 3 };
Ā Ā Ā Ā int K = 2;
Ā 
Ā Ā Ā Ā int ans = solve(arr, K);
Ā Ā Ā Ā System.out.println(ans);
Ā Ā }
}
Ā 
// This code is contributed by Saurabh Jaiswal


Python3




# Python program for the above approach
Ā 
# Function to find the minimum jumps
def solve(arr, K):
Ā Ā Ā Ā size = len(arr)
Ā Ā Ā Ā dp = [0] * (size)
Ā 
Ā Ā Ā Ā # Initially only a single element
Ā Ā Ā Ā dp[0] = arr[0]
Ā 
Ā Ā Ā Ā for idx in range(1, size, 1):
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā # At most k elements backwards
Ā Ā Ā Ā Ā Ā Ā Ā end = max(-1, idx - K - 1)
Ā Ā Ā Ā Ā Ā Ā Ā mini = float('inf')
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā # Find minimum among all the values
Ā Ā Ā Ā Ā Ā Ā Ā for ptr in range(idx - 1, end, -1):
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā mini = min(mini, dp[ptr])
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā dp[idx] = arr[idx] + mini
Ā 
Ā Ā Ā Ā # Return cost to reach the
Ā Ā Ā Ā # last index of array
Ā Ā Ā Ā return (dp[-1])
Ā 
Ā 
# Driver Code
if __name__ == "__main__":
Ā Ā Ā Ā arr = [2, 4, 1, 6, 3]
Ā Ā Ā Ā K = 2
Ā 
Ā Ā Ā Ā ans = solve(arr, K)
Ā Ā Ā Ā print(ans)


C#




//Ā  C# program for the above approach
using System;
class GFG
{
Ā Ā Ā 
//Ā  Function to find the minimum jumps
static int solve(int []arr, int K)
{
Ā Ā int size = arr.Length;
Ā Ā int []dp = new int[size];
Ā Ā Ā 
Ā Ā for(int i = 0; i < size; i++) {
Ā Ā Ā Ā dp[i] = 0;
Ā Ā }
Ā 
Ā Ā //Ā  Initially only a single element
Ā Ā dp[0] = arr[0];
Ā 
Ā Ā for (int idx = 1; idx < size; idx++) {
Ā 
Ā Ā Ā Ā //Ā  At most k elements backwards
Ā Ā Ā Ā int end = Math.Max(-1, idx - K - 1);
Ā Ā Ā Ā int mini = Int32.MaxValue;
Ā 
Ā Ā Ā Ā //Ā  Find minimum among all the values
Ā Ā Ā Ā for (int ptr = idx - 1; ptr > end; ptr--) {
Ā Ā Ā Ā Ā Ā mini = Math.Min(mini, dp[ptr]);
Ā Ā Ā Ā }
Ā Ā Ā Ā dp[idx] = arr[idx] + mini;
Ā Ā }
Ā Ā Ā 
Ā Ā //Ā  Return cost to reach the
Ā Ā //Ā  last index of array
Ā Ā return dp[size - 1];
}
Ā 
//Ā  Driver Code
public static void Main()
{
Ā Ā int []arr = { 2, 4, 1, 6, 3 };
Ā Ā int K = 2;
Ā 
Ā Ā int ans = solve(arr, K);
Ā Ā Console.WriteLine(ans);
}
}
Ā 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
Ā Ā Ā Ā Ā Ā // JavaScript code for the above approach
Ā 
Ā Ā Ā Ā Ā Ā // Function to find the minimum jumps
Ā Ā Ā Ā Ā Ā function solve(arr, K) {
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā let size = arr.length
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā let dp = new Array(size + 1).fill(0)
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Initially only a single element
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā dp[0] = arr[0]
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for (let idx = 1; idx < size; idx++) {
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // At most k elements backwards
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā let end = Math.max(-1, idx - K - 1)
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā let mini = Number.MAX_VALUE
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Find minimum among all the values
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for (let ptr = idx - 1; ptr > end; ptr--)
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā mini = Math.min(mini, dp[ptr])
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā dp[idx] = arr[idx] + mini
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Return cost to reach the
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // last index of array
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā return dp[size - 1]
Ā 
Ā Ā Ā Ā Ā Ā }
Ā Ā Ā Ā Ā Ā Ā 
Ā Ā Ā Ā Ā Ā // Driver Code
Ā Ā Ā Ā Ā Ā let arr = [2, 4, 1, 6, 3]
Ā Ā Ā Ā Ā Ā let K = 2
Ā 
Ā Ā Ā Ā Ā Ā ans = solve(arr, K)
Ā Ā Ā Ā Ā Ā document.write(ans)
Ā 
Ā Ā Ā Ā Ā // This code is contributed by Potta Lokesh
Ā Ā </script>


Output:Ā 

6

Ā 

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

Efficient Approach: Instead of calculating the minimum cost for each index, use the sliding window approach. Use the sliding window of size K, such that the minimum element is always present at the front and sorted order is maintained. Follow the below steps to solve the problem:

  • Initialize deque to hold the data, as it supports the efficient operation of popping elements from both front and backside.
  • Insert the first element along with its index in the deque. The index is also inserted to track if any element is within the window limit of size K.
  • Then, start looping from index 1 till the end of the array. For each index, remove all the elements from the front which are out of the current window size, i.e difference between indices > k.
  • Calculate current_value as the summation of arr[i] and the first value of dequeue. Here the first value is added, because it is the smallest value in the current window.
  • Then pop all the elements from the back from deque which has a value greater than or equal to current_value. This is done to maintain a sorted order in the deque.
  • Finally return the last value in the deque, showing the cost to reach the last index of the array.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
Ā 
// Function to find the minimum jumps
int solve(int arr[], int K, int size)
{
Ā Ā deque<pair<int, int> > ququ;
Ā 
Ā Ā // Insert index and value
Ā Ā ququ.push_back({ 0, arr[0] });
Ā 
Ā Ā for (int i = 1; i < size; i++) {
Ā Ā Ā Ā // Remove elements from front
Ā Ā Ā Ā // which are out of curr_window size
Ā Ā Ā Ā while ((ququ.size() > 0)
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā && ((i - ququ.front().first) > K))
Ā Ā Ā Ā Ā Ā ququ.pop_front();
Ā 
Ā Ā Ā Ā int curr_val = arr[i] + ququ.front().second;
Ā 
Ā Ā Ā Ā // Pop greater elements from back
Ā Ā Ā Ā while ((ququ.size() > 0)
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā && (curr_val <= ququ.back().second))
Ā Ā Ā Ā Ā Ā ququ.pop_back();
Ā 
Ā Ā Ā Ā // Append index and curr_val
Ā Ā Ā Ā ququ.push_back({ i, curr_val });
Ā Ā }
Ā 
Ā Ā // Finally return last value
Ā Ā // indicating cost to reach the last index
Ā Ā return ququ.back().second;
}
Ā 
// driver code
int main()
{
Ā Ā int arr[] = { 2, 4, 1, 6, 3 };
Ā Ā int K = 2;
Ā Ā int size = sizeof(arr) / sizeof(arr[0]);
Ā 
Ā Ā int ans = solve(arr, K, size);
Ā Ā cout << ans << endl;
Ā Ā return 0;
}
Ā 
// This code is contributed by Palak Gupta


Java




import java.util.*;
import java.io.*;
Ā 
// Java program for the above approach
class GFG{
Ā 
Ā Ā // Function to find the minimum jumps
Ā Ā public static int solve(int arr[], int K, int size)
Ā Ā {
Ā Ā Ā Ā Deque<pair> ququ = new LinkedList<pair>();
Ā 
Ā Ā Ā Ā // Insert index and value
Ā Ā Ā Ā ququ.addLast(new pair(0, arr[0]));
Ā 
Ā Ā Ā Ā for (int i = 1 ; i < size ; i++) {
Ā Ā Ā Ā Ā Ā // Remove elements from front
Ā Ā Ā Ā Ā Ā // which are out of curr_window size
Ā Ā Ā Ā Ā Ā while ((ququ.size() > 0) && ((i - ququ.getFirst().x) > K))
Ā Ā Ā Ā Ā Ā Ā Ā ququ.removeFirst();
Ā 
Ā Ā Ā Ā Ā Ā int curr_val = arr[i] + ququ.getFirst().y;
Ā 
Ā Ā Ā Ā Ā Ā // Pop greater elements from back
Ā Ā Ā Ā Ā Ā while ((ququ.size() > 0) && (curr_val <= ququ.getLast().y))
Ā Ā Ā Ā Ā Ā Ā Ā ququ.removeLast();
Ā 
Ā Ā Ā Ā Ā Ā // Append index and curr_val
Ā Ā Ā Ā Ā Ā ququ.addLast(new pair(i, curr_val));
Ā Ā Ā Ā }
Ā 
Ā Ā Ā Ā // Finally return last value
Ā Ā Ā Ā // indicating cost to reach the last index
Ā Ā Ā Ā return ququ.getLast().y;
Ā Ā }
Ā 
Ā Ā // Driver code
Ā Ā public static void main(String args[])
Ā Ā {
Ā Ā Ā Ā int arr[] = { 2, 4, 1, 6, 3 };
Ā Ā Ā Ā int K = 2;
Ā Ā Ā Ā int size = arr.length;
Ā 
Ā Ā Ā Ā int ans = solve(arr, K, size);
Ā Ā Ā Ā System.out.println(ans);
Ā Ā }
}
Ā 
class pair{
Ā Ā Integer x;
Ā Ā Integer y;
Ā 
Ā Ā pair(int a,int b){
Ā Ā Ā Ā this.x = a;
Ā Ā Ā Ā this.y = b;
Ā Ā }
}
Ā 
// This code is contributed by subhamgoyal2014.


Python3




# Python program for the above approach
from collections import deque
Ā 
# Function to find the minimum jumps
def solve(arr, K):
Ā Ā Ā Ā size = len(arr)
Ā Ā Ā Ā ququ = deque()
Ā 
Ā Ā Ā Ā # Insert index and value
Ā Ā Ā Ā ququ.append((0, arr[0]))
Ā 
Ā Ā Ā Ā for i in range(1, size, 1):
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā # Remove elements from front
Ā Ā Ā Ā Ā Ā Ā Ā # which are out of curr_window size
Ā Ā Ā Ā Ā Ā Ā Ā while(ququ and i - ququ[0][0] > K):
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ququ.popleft()
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā curr_val = arr[i] + ququ[0][1]
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā # Pop greater elements from back
Ā Ā Ā Ā Ā Ā Ā Ā while(ququ and curr_val <= ququ[-1][1]):
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ququ.pop()
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā # Append index and curr_val
Ā Ā Ā Ā Ā Ā Ā Ā ququ.append((i, curr_val))
Ā 
Ā Ā Ā Ā # Finally return last value
Ā Ā Ā Ā # indicating cost to reach the last index
Ā Ā Ā Ā return ququ[-1][1]
Ā 
Ā 
# Driver Code
if __name__ == "__main__":
Ā Ā Ā Ā arr = [2, 4, 1, 6, 3]
Ā Ā Ā Ā K = 2
Ā 
Ā Ā Ā Ā ans = solve(arr, K)
Ā Ā Ā Ā print(ans)


C#




// C# program for the above approach
Ā 
Ā 
using System;
using System.Collections.Generic;
Ā 
class GFG
{
Ā 
Ā Ā Ā Ā class pair
Ā Ā Ā Ā {
Ā Ā Ā Ā Ā Ā Ā Ā public int x, y;
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā public pair(int a, int b)
Ā Ā Ā Ā Ā Ā Ā Ā {
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.x = a;
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā this.y = b;
Ā Ā Ā Ā Ā Ā Ā Ā }
Ā Ā Ā Ā }
Ā 
Ā Ā Ā Ā // Function to find the minimum jumps
Ā Ā Ā Ā public static int solve(int[] arr, int K, int size)
Ā Ā Ā Ā {
Ā Ā Ā Ā Ā Ā Ā Ā LinkedList<pair> ququ = new LinkedList<pair>();
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā // Insert index and value
Ā Ā Ā Ā Ā Ā Ā Ā ququ.AddLast(new pair(0, arr[0]));
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā for (int i = 1; i < size; i++)
Ā Ā Ā Ā Ā Ā Ā Ā {
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Remove elements from front
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // which are out of curr_window size
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā while ((ququ.Count > 0) && ((i - ququ.First.Value.x) > K))
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ququ.RemoveFirst();
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā int curr_val = arr[i] + ququ.First.Value.y;
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Pop greater elements from back
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā while ((ququ.Count > 0) && (curr_val <= ququ.Last.Value.y))
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ququ.RemoveLast();
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Append index and curr_val
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ququ.AddLast(new pair(i, curr_val));
Ā Ā Ā Ā Ā Ā Ā Ā }
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā // Finally return last value
Ā Ā Ā Ā Ā Ā Ā Ā // indicating cost to reach the last index
Ā Ā Ā Ā Ā Ā Ā Ā return ququ.Last.Value.y;
Ā Ā Ā Ā }
Ā 
Ā Ā Ā Ā // Driver code
Ā Ā Ā Ā public static void Main()
Ā Ā Ā Ā {
Ā Ā Ā Ā Ā Ā Ā Ā int[] arr = { 2, 4, 1, 6, 3 };
Ā Ā Ā Ā Ā Ā Ā Ā int K = 2;
Ā Ā Ā Ā Ā Ā Ā Ā int size = arr.Length;
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā int ans = solve(arr, K, size);
Ā Ā Ā Ā Ā Ā Ā Ā Console.Write(ans);
Ā Ā Ā Ā }
}
Ā 
Ā 
Ā 
// This code is contributed by Saurabh Jaiswal


Javascript




// Javascript program for the above approach
Ā 
// Function to find the minimum jumps
function solve(arr, K, size)
{
ququ = [];
Ā 
// Insert index and value
ququ.push({ "first" :0,
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā "second" : arr[0] });
Ā 
for (let i = 1; i < size; i++) {
Ā Ā Ā Ā // Remove elements from front
Ā Ā Ā Ā // which are out of curr_window size
Ā Ā Ā Ā while ((ququ.length > 0)
Ā Ā Ā Ā Ā Ā Ā Ā && ((i - ququ[0].first) > K))
Ā Ā Ā Ā ququ.shift();
Ā 
Ā Ā Ā Ā let curr_val = arr[i] + ququ[0].second;
Ā 
Ā Ā Ā Ā // Pop greater elements from back
Ā Ā Ā Ā while ((ququ.length > 0)
Ā Ā Ā Ā Ā Ā Ā Ā && (curr_val <= ququ[ququ.length-1].second))
Ā Ā Ā Ā ququ.pop();
Ā 
Ā Ā Ā Ā // Append index and curr_val
Ā Ā Ā Ā ququ.push({"first" : i,
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā "second" : curr_val });
}
Ā 
// Finally return last value
// indicating cost to reach the last index
return ququ[ququ.length-1].second;
}
Ā 
// driver code
let arr = [ 2, 4, 1, 6, 3 ];
let K = 2;
let size = arr.length;
Ā 
let ans = solve(arr, K, size);
console.log(ans);
Ā 
// This code is contributed by akashish__


Output

6

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments