Frog with k jumps
Problem
There are stones, numbered . For each , the height of Stone is .
There is a frog who is initially on Stone . He will repeat the following action some number of times to reach Stone :
- If the frong is currently on stone , jump to one of following: Stone . Here, a cost of is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone .
Solution Approach
Expected Time Complexity:
Click - to see solution code
- C++
void solve() {
cin >> n >> k;
vl a(n);
for (int i = 0; i < n; i++) cin >> a[i];
vl ans(n, INT_MAX);
ans[0] = 0;
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0 && j >= i - k; j--) {
ans[i] = min(ans[i], abs(a[i] - a[j]) + ans[j]);
}
}
cout << ans[n - 1];
}