There are N villages, numbered from 1, 2, to N. There is a cost c_i associated with every village. There is a person standing at village 1. He will repeat the following action some number of times to reach the last village (N). If the person is at the village i, he can directly reach village i+1, i+2, i+3, …, i+K. Cost incurred is |c_i – c_j| , where j is the village where he reached from village i. Find the minimum possible cost incurred to reach village N.
Examples :
Input : 5 3 10 30 40 50 20 Output : 30 Here, N = 5, number of villages K = 3 Take the path 1 -> 2 -> 5, incurring total cost = |10 - 30| + |30 - 20| = 30 Input : 2 100 10 10 Output : 0 N = 2, K = 100 There is only one path 1 -> 2, incurring total cost as 0.
This can be solved using dynamic programming. The following steps are taken to solve it: 1. Initialize an empty array of size n to store answer at every index. 2. It is given that the person is already standing at village 1, therefore dp[0] = 0. 3. Now, for every index i >= 1, there are various possibility to reach i i.e, from i – 1, … i – K 4. For every index i, we need to find the minimum cost to reach i from j, where j = i – 1, i – 2, .. i – k, i – j <= k is used to make sure we remain within k length and j can become negative, we also have to add this condition. The code is written below using the above concept.
Implementation :
#include <bits/stdc++.h>
using namespace std;
// helper function to find the minimum cost to reach the end
int minCost(int* arr, int n, int k)
{
int* dp = new int[n];
// fills dp array with 0
memset(dp, 0, n * sizeof(int));
// for finding answer for each index
for (int i = 1; i < n; i++) {
// temp will store the temporary answer
// ans will store the final answer which will be stored at dp[i]
int ans = INT_MAX, temp = INT_MAX;
// for each index i, we can reach i from i - 1, i - 2, ... i - k
// i - j <= k will check that we don't reach beyond i - k
// j >= 0 will make sure that we don't reach negative index
for (int j = i - 1; j >= 0 && i - j <= k; j--) {
temp = dp[j] + abs(arr[i] - arr[j]);
if (temp < ans)
ans = temp;
}
// storing final answer to dp[i]
dp[i] = ans;
}
return dp[n - 1];
}
// function to handle input and output
int main()
{
int n = 5, k = 3;
int a[] = { 10, 30, 40, 50, 20 };
cout << minCost(a, n, k);
return 0;
}
Time Complexity : O(NK) Space complexity: O(N)