Frog jump with K distances
Pattern: 1D DP
Like Frog Jump, but a jump can cover up to k stones. The cheapest way to stone i is the cheapest of the k stones before it plus the cost of jumping from there.
The problem
A frog may jump up to k stones forward; a jump costs the height difference. Return the least total cost from stone 0 to the last stone. [10, 30, 40, 50, 20] with k = 3 gives 30.
Think first
- How many stones could the last jump start from?
- What changes from the 2-stone version?
- What does it cost?
Hints
Brute force, and why it fails
Try every sequence of jumps: exponential.
The key insight
Each stone's best cost depends only on the k stones before it.
Dry run
| best | 0 20 30 |
|---|
heights [10, 30, 40, 50, 20], k = 3. best = 0, 20, 30.
Step 1 of 3
The plan
best[0] = 0
for i: best[i] = min over j in 1..k with i - j >= 0 of best[i - j] + |h[i] - h[i - j]|
Complexity
- Time
O(n × k)- Space
O(n)
k choices per stone.
Edge cases
- k = 1: one path.
- k at least n: can jump anywhere.
- One stone: 0.
I've built my logic, show the code
Java
class Solution {
public int frogJumpK(int[] heights, int k) {
int n = heights.length;
int[] best = new int[n]; // best[i]: least energy to reach stone i
for (int i = 1; i < n; i++) {
best[i] = Integer.MAX_VALUE;
for (int j = 1; j <= k && i - j >= 0; j++) // the last jump came from one of the k stones before
best[i] = Math.min(best[i], best[i - j] + Math.abs(heights[i] - heights[i - j]));
}
return best[n - 1];
}
}C++
class Solution {
public:
int frogJumpK(vector<int>& heights, int k) {
int n = static_cast<int>(heights.size());
vector<int> best(n, 0); // best[i]: least energy to reach stone i
for (int i = 1; i < n; i++) {
best[i] = INT_MAX;
for (int j = 1; j <= k && i - j >= 0; j++) // the last jump came from one of the k stones before
best[i] = min(best[i], best[i - j] + abs(heights[i] - heights[i - j]));
}
return best[n - 1];
}
};Python
class Solution:
def frogJumpK(self, heights: list[int], k: int) -> int:
best = [0] * len(heights) # best[i]: least energy to reach stone i
for i in range(1, len(heights)):
best[i] = min(best[i - j] + abs(heights[i] - heights[i - j]) for j in range(1, k + 1) if i - j >= 0) # from k before
return best[-1]Common mistakes
- Looking before stone 0.
- Using only the k-th previous stone.