- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 44 lines of Java from the credited upstream file 656-2.java.
- The implementation visibly relies on sequence storage, cached states.
- 3 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<Integer> cheapestJump(int[] coins, int maxJump) {3 if (coins[coins.length - 1] == -1)4 return new ArrayList<>();5 6 final int n = coins.length;7 8 int[] dp = new int[n];9 int[] next = new int[n];10 11 Arrays.fill(dp, Integer.MAX_VALUE);12 Arrays.fill(next, -1);13 14 dp[n - 1] = coins[n - 1];15 16 for (int i = n - 2; i >= 0; --i) {17 if (coins[i] == -1)18 continue;19 for (int j = i + 1; j < Math.min(i + maxJump + 1, n); ++j) {20 if (dp[j] == Integer.MAX_VALUE)21 continue;22 final int cost = coins[i] + dp[j];23 if (cost < dp[i]) {24 dp[i] = cost;25 next[i] = j;26 }27 }28 }29 30 if (dp[0] == Integer.MAX_VALUE)31 return new ArrayList<>();32 return constructPath(next, 0);33 }34 35 private List<Integer> constructPath(int[] next, int i) {36 List<Integer> ans = new ArrayList<>();37 while (i != -1) {38 ans.add(i + 1); 39 i = next[i];40 }41 return ans;42 }43}44