Coin Path — LeetCode 656 Python Solution
- Problem
- #656
- Pattern
- Dynamic Programming
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given an integer array coins (1-indexed) of length n and an integer maxJump. You can jump to any index i of the array coins if coins[i] != -1 and you have to pay coins[i] when you visit index i.
Example
- Input
- coins = [1,2,4,-1,2], maxJump = 2
- Output
- [1,3,5]
Python solution
class Solution:
def cheapestJump(self, coins: List[int], maxJump: int) -> List[int]:
if coins[-1] == -1:
return []
n = len(coins)
f = [inf] * n
f[-1] = coins[-1]
for i in range(n - 2, -1, -1):
if coins[i] != -1:
for j in range(i + 1, min(n, i + maxJump + 1)):
if f[i] > f[j] + coins[i]:
f[i] = f[j] + coins[i]
if f[0] == inf:
return []
ans = []
s = f[0]
for i in range(n):
if f[i] == s:
s -= coins[i]
ans.append(i + 1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 656. Coin Path is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 656. Coin Path?
- LeetCode 656. Coin Path is rated Hard on LeetCode.
- What topics does LeetCode 656. Coin Path cover?
- LeetCode 656. Coin Path is tagged Array and Dynamic Programming on LeetCode.
- Is LeetCode 656. Coin Path a premium problem?
- Yes. LeetCode 656. Coin Path is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.