Wednesday, 27 Oct 2021

# Minimize cost to reach end of an array by two forward jumps or one backward jump in each move

Minimize cost to reach end of an array by two forward jumps or one backward jump in each move
Given an array arr[] consisting of N positive integers, the task is to find the minimum cost required to either cross the array or reach the end of the array by only moving to indices (i + 2) and (i – 1) from the ith index.
Examples:

Input: arr[] = {5, 1, 2, 10, 100}Output: 18Explanation:Optimal cost path (0 based indexing): 0 → 2 → 1 → 3 → 5Therefore, the minimum cost = 5 + 2 + 1 + 10 = 18.
Input: arr[] = {9, 4, 6, 8, 5}Output: 20Explanation:Optimal cost path (0 based indexing): 0 → 2 → 4Therefore, the minimum cost = 9 + 6 + 5 = 20

Naive Approach: The given problem can be solved based on the following observations:Since all costs are positive, it will never be an optimal option to move more than one step backward, hence to reach a particular index i of the array, either jump directly from the (i – 2)thindex or jump from (i – 1)thto (i + 1)th index, i.e. (2 jumps forward), followed by 1 backward jump, i.e. from (i + 1)th index to ith index.
Now, traverse from the end of the array recursively and for the elements at indices (i – 2) and (i – 1), calculate the minimum cost of the two. Therefore, the minimum cost to cross the array can be calculated using the following recurrence relation:

minCost(index) = minimum(minCost(index – 2) + arr[i], minCost(index – 1) + arr[i] + arr[i + 1])

Time Complexity: O(2N)Auxiliary Space: O(1)
Efficient Approach: The approach discussed above has both Optimal Substructure and Overlapping Subproblems. Therefore it can be optimized by either using Memoization or Tabulation. Follow the steps below to solve the problem:
Initialize an array dp[], where dp[i] stores the minimum cost to reach the ith index.
Initialize dp = arr as the cost to reach the 0th index, which is equal to the value at the 0th index itself. Update dp = arr + arr + arr, as to reach the 1st index, jump from the 0th index to 2nd index indexn to the 1st index.
Iterate over the range [2, N – 2] using a variable i and update dp[i] as the minimum of (dp[i – 2] + arr[i]) and (dp[i – 1] + arr[i] + arr[i + 1]).
For the last index (N – 1), update dp[N – 1] as minimum of (dp[N – 3] + arr[N – 1]) and (dp[N – 2]).
After completing the above steps, print the value of dp[N – 1] as the result.
Below is the implementation of the above approach:

C++

#include
using namespace std;

void minCost(int arr[], int n)
{

if (n < 3) {         cout