File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n * B)
2
+ // Space: O(n)
3
+
4
+ class Solution {
5
+ public:
6
+ vector<int > cheapestJump (vector<int >& A, int B) {
7
+ vector<int > result;
8
+ if (A.empty () || A.back () == -1 ) {
9
+ return result;
10
+ }
11
+ const int n = A.size ();
12
+ vector<int > dp (n, numeric_limits<int >::max ()), next (n, -1 );
13
+ dp[n - 1 ] = A[n - 1 ];
14
+ for (int i = n - 2 ; i >= 0 ; --i) {
15
+ if (A[i] == -1 ) {
16
+ continue ;
17
+ }
18
+ for (int j = i + 1 ; j <= min (i + B, n - 1 ); ++j) {
19
+ if (dp[j] == numeric_limits<int >::max ()) {
20
+ continue ;
21
+ }
22
+ if (A[i] + dp[j] < dp[i]) {
23
+ dp[i] = A[i] + dp[j];
24
+ next[i] = j;
25
+ }
26
+ }
27
+ }
28
+ if (dp[0 ] == numeric_limits<int >::max ()) {
29
+ return result;
30
+ }
31
+ int k = 0 ;
32
+ while (k != -1 ) {
33
+ result.emplace_back (k + 1 );
34
+ k = next[k];
35
+ }
36
+ return result;
37
+ }
38
+ };
You can’t perform that action at this time.
0 commit comments