656 Coin Path
656. Coin Path
1. Question
Input: [1,2,4,-1,2], 2
Output: [1,3,5]Input: [1,2,4,-1,2], 1
Output: []2. Implementation
3. Time & Space Complexity
Last updated
Input: [1,2,4,-1,2], 2
Output: [1,3,5]Input: [1,2,4,-1,2], 1
Output: []Last updated
class Solution {
public List<Integer> cheapestJump(int[] A, int B) {
List<Integer> res = new ArrayList<>();
if (A == null || A.length == 0 || A[A.length - 1] == -1) {
return res;
}
int n = A.length;
// dp[i] is the min cost to reach position i from the start
int[] dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[n - 1] = A[n - 1];
// preIndex[i] store the previous index of i in the min cost path
int[] preIndex = new int[n];
Arrays.fill(preIndex, -1);
for (int i = n - 2; i >= 0; i--) {
// Ignore position we cannot reach
if (A[i] == -1) continue;
for (int j = i + 1; j <= Math.min(i + B, n - 1); j++) {
if (dp[j] == Integer.MAX_VALUE) continue;
if (A[i] + dp[j] < dp[i]) {
dp[i] = A[i] + dp[j];
preIndex[i] = j;
}
}
}
// Cannot reach A[n - 1] from A[0]
if (dp[0] == Integer.MAX_VALUE) {
return res;
}
for (int index = 0; index != -1; index = preIndex[index]) {
res.add(index + 1);
}
return res;
}
}