Coin Path - Problem
Imagine navigating through a platformer game where you start at the first platform and need to reach the final platform with the minimum cost. You have a limited jump range and must pay a toll to land on each platform!
Given a 1-indexed array coins where coins[i] represents the cost to land on platform i (or -1 if blocked), and an integer maxJump representing your maximum jump distance, find the lexicographically smallest path that reaches the final platform with minimum cost.
Rules:
- Start at index 1 (guaranteed to be accessible)
- From index
i, you can jump to any indexi + kwhere1 ≤ k ≤ maxJump - Cannot land on blocked platforms (where
coins[i] = -1) - Pay
coins[i]cost when visiting indexi - If multiple paths have the same minimum cost, return the lexicographically smallest one
Example: coins = [1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, 0], maxJump = 6
You can jump from index 1 → 10 → 16 with total cost 1+0+0 = 1
Input & Output
example_1.py — Basic Path Finding
$
Input:
coins = [1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, 0], maxJump = 6
›
Output:
[1, 10, 16]
💡 Note:
Start at index 1 (cost 1), jump to index 10 (cost 0), then jump to index 16 (cost 0). Total cost = 1 + 0 + 0 = 1. This is the minimum cost path.
example_2.py — Lexicographically Smallest Path
$
Input:
coins = [1, 2, 4, -1, 2], maxJump = 2
›
Output:
[1, 3, 5]
💡 Note:
Two paths exist: [1,3,5] with cost 1+4+2=7 and [1,2,5] with cost 1+2+2=5. The second path has lower cost, but we need to check if [1,3,5] is also optimal. Actually [1,2,5] is cheaper, so answer is [1,2,5].
example_3.py — Impossible Path
$
Input:
coins = [1, 2, -1], maxJump = 1
›
Output:
[]
💡 Note:
Cannot reach the end because index 3 (coins[2]) is blocked with value -1, and maxJump=1 means we can only jump 1 position at a time.
Constraints
- 1 ≤ coins.length ≤ 1000
- 0 ≤ coins[i] ≤ 109 or coins[i] = -1
- 1 ≤ maxJump ≤ 1000
- coins[0] ≠ -1 (starting position is always accessible)
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Costs
Set up DP array where dp[i] represents minimum cost to reach platform i
2
Forward Pass
For each platform, calculate costs to reach all platforms within jumping distance
3
Backward Reconstruction
Starting from the end, trace back the optimal path by choosing lexicographically smallest jumps
4
Return Path
Output the complete path from start to end platform
Key Takeaway
🎯 Key Insight: Use DP for cost optimization, then reconstruct the lexicographically smallest path by working backwards and greedily choosing the smallest valid previous position at each step.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code