Minimum Cost to Reach End
You are given an array “ARR” of 'N' integers and an integer 'K'. You can move from any index 'i' to index 'j' if j ≤ i + K. The cost of moving from one index 'i' to the other index 'j' is abs(ARR[j] – ARR[i]). Your task is to find the minimum cost to reach the end of the array from the beginning of the array when a maximum jump of 'K' is allowed.
For example:
If the given array is [10, 3, 40, 5, 25] and K is 2 then the minimum cost would be 29.
Since K = 2, the optimal way to reach the end of the array with minimum cost is to take a jump to 1st index from 0th index with the cost of abs(3 - 10) i.e 7 and then we take a jump of 2 from 1st index to the 3rd index with the cost of abs(5 - 3). i.e 2. Then we take a jump of 1 from 3rd index to the last index with the cost of abs(25 - 5) .ie 20.
Therefore the minimum cost to reach the end of the array is (7 + 2 + 20) i.e 29.
Input format :
The first line of input contains a single integer 'T', representing the number of test cases or queries to be run.
Then the 'T' test cases follow.
The first line of each test case contains two single space-separated integers 'N', and 'K', denoting the size of the array and the maximum jump allowed from any index.
The second line of each test case contains 'N' single space-separated integers, elements of the array.
Output format :
For each test case, print a single line containing a single integer denoting the minimum cost, in a single line.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
2 <= N <= 1000
1 <= K < N
0 <= ARR[i] <= 10 ^ 6
Time Limit: 1 sec.
CodingNinjas
author
2y
Dynamic Programming
The idea is to use a bottom-up dynamic programming approach instead of a memoization approach. In this, we use the recurrence relation of memoization approach as dp(j) = min{dp(i) +...read more
Help your peers!
Add answer anonymously...
Top Visa Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Visa Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app