|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| - |
4 | 3 | import java.util.ArrayList;
|
5 | 4 | import java.util.Arrays;
|
6 | 5 | import java.util.List;
|
|
35 | 34 | */
|
36 | 35 |
|
37 | 36 | public class _656 {
|
| 37 | + public static class Solution1 { |
38 | 38 |
|
39 |
| - /** |
40 |
| - * Time: O(n*B) |
41 |
| - * Reference: https://leetcode.com/articles/coin-path/#approach-3-using-dynamic-programming-accepted |
42 |
| - */ |
43 |
| - public List<Integer> cheapestJump(int[] A, int B) { |
44 |
| - int[] next = new int[A.length]; |
45 |
| - long[] dp = new long[A.length]; |
46 |
| - Arrays.fill(next, -1); |
47 |
| - List<Integer> res = new ArrayList(); |
48 |
| - for (int i = A.length - 2; i >= 0; i--) { |
49 |
| - long minCost = Integer.MAX_VALUE; |
50 |
| - for (int j = i + 1; j <= i + B && j < A.length; j++) { |
51 |
| - if (A[j] >= 0) { |
52 |
| - long cost = A[i] + dp[j]; |
53 |
| - if (cost < minCost) { |
54 |
| - minCost = cost; |
55 |
| - next[i] = j; |
| 39 | + /** |
| 40 | + * Time: O(n*B) |
| 41 | + * Reference: https://leetcode.com/articles/coin-path/#approach-3-using-dynamic-programming-accepted |
| 42 | + */ |
| 43 | + public List<Integer> cheapestJump(int[] A, int B) { |
| 44 | + int[] next = new int[A.length]; |
| 45 | + long[] dp = new long[A.length]; |
| 46 | + Arrays.fill(next, -1); |
| 47 | + List<Integer> res = new ArrayList(); |
| 48 | + for (int i = A.length - 2; i >= 0; i--) { |
| 49 | + long minCost = Integer.MAX_VALUE; |
| 50 | + for (int j = i + 1; j <= i + B && j < A.length; j++) { |
| 51 | + if (A[j] >= 0) { |
| 52 | + long cost = A[i] + dp[j]; |
| 53 | + if (cost < minCost) { |
| 54 | + minCost = cost; |
| 55 | + next[i] = j; |
| 56 | + } |
56 | 57 | }
|
57 | 58 | }
|
| 59 | + dp[i] = minCost; |
58 | 60 | }
|
59 |
| - dp[i] = minCost; |
60 |
| - } |
61 |
| - int i; |
62 |
| - for (i = 0; i < A.length && next[i] > 0; i = next[i]) { |
63 |
| - res.add(i + 1); |
64 |
| - } |
65 |
| - if (i == A.length - 1 && A[i] >= 0) { |
66 |
| - res.add(A.length); |
67 |
| - } else { |
68 |
| - return new ArrayList<>(); |
| 61 | + int i; |
| 62 | + for (i = 0; i < A.length && next[i] > 0; i = next[i]) { |
| 63 | + res.add(i + 1); |
| 64 | + } |
| 65 | + if (i == A.length - 1 && A[i] >= 0) { |
| 66 | + res.add(A.length); |
| 67 | + } else { |
| 68 | + return new ArrayList<>(); |
| 69 | + } |
| 70 | + return res; |
69 | 71 | }
|
70 |
| - return res; |
71 | 72 | }
|
72 | 73 | }
|
0 commit comments